269200 Web Programming Language Week 9 Dr. Ken Cosh Introducing jQuery
What is jQuery
• jQuery is a Javascript Library
• It makes Javascript a lot simpler
• It’s easy to learn
• There are other js frameworks out there, but jQuery has become the most popular.
What is Jquery?
• HTML / DOM manipulation
• CSS manipulation
• HTML event methods
• Effects & Animations
• AJAX
Installing jQuery
• You can download it from jQuery.com
<head><script src="jquery-1.11.1.min.js"></script>
</head>
• Or use one hosted by Google
<head><script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></
script></head>
• Why might it be a good idea to host it yourself?
• Why might it be a good idea to use Google's one?
jQuery syntax
• Essentially jQuery lets you select HTML elements and perform some action on them.
$(selector).action()
• $ - sign to define jquery
• selector – to query or find HTML elements
• action – function to perform on the elements
Is the document ready?
• Most jQuery exists within a ‘document ready event’
$(document).ready(function() {
//code here
});
• This makes sure that jQuery functions don’t run until the whole page is loaded.
• What would happen if you tried to hide an element that hasn’t yet been loaded?
Selectors
• Remember “getElementById()”?
• This is replaced with “$”
• jQuery selectors allow us to find and select specific HTML elements
• based on their id, class, attributes, values of attributes etc.
Example 1
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").hide();
});
});
</script>
</head>
<body>
<h2>This is a heading</h2>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<button>Click me</button>
</body>
</html>
Example 2 – Select by ID
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").hide();
});
});
</script>
More Selectors• What do you think they do?
$(“*”)
$(this)
$(“p.intro”)
$(“p:first”)
$(“ul li:first”)
$(“ul li:first-child”)
$(“[href]”)
$(“a[target=‘_blank’]”)
$(“a[target!=‘_blank’]”)
$(“tr:even”)
$(“tr:odd”)
Events
• Events are a page visitors action that we can respond to.
• Moving a mouse over an element
• Clicking on an element
Events
• Mouse Events
• click
• dblclick
• mouseenter
• mouseleave
• Keyboard Events
• keypress
• keydown
• keyup
• Form Events
• submit
• change
• focus
• blur
• Document Events
• load
• resize
• scroll
• unload
Example(s)
<script>
$(document).ready(function(){
$("p").click(function(){
$(this).hide();
});
});
</script>
hide(), show() & toggle()
• We can make elements appear and disappear using ‘hide()’ and ‘show()’
• The syntax is:$(selector).hide(speed, callback);
• speed is either “slow”, “fast” or a number in miliseconds
• callback is a function to call when the task is complete (more later)
• What if you don’t know if the element is visible or not?
• You can call ‘toggle()’
fade
• Fade has several options;
• fadeIn()
• fadeOut()
• fadeToggle()
• fadeTo()
• fadeTo has 3 parameters (speed, opacity & callback)
Animate
• animate() is used to create custom animations$(selector).animate({params}, speed, callback);
params refers to the css properties to be animated
(speed and callback are optional)
Animate()
• You can animate multiple properties at once…
• You can animate using ‘relative’ values…
• You can animate things in a queue…
• or you can stop() animations partway through…
Callbacks
• Callbacks are functions that are called when the current effect is complete.
• If we have an animation we may want to wait until it is finished and then call another function
$("button").click(function(){ $("p").hide("slow",function(){ alert("The paragraph is now hidden"); });
});
Chaining
• Chaining is when a series of methods are called one after each other
• We can run multiple commands within a single statement
• This saves us searching for the same element more than once
$("#p1").css("color","red").slideUp(2000).slideDown(2000);
• Note, we could write this;
$("#p1").css("color","red") .slideUp(2000) .slideDown(2000);
DOM Manipulation
• jQuery offers us a great way to manipulate the DOM.
• i.e. access (get) and change (set) elements and attributes
• There are some important functions
• text()
• html()
• val()
• attr()
text()
• text() sets or returns the text content of a particular element
• get
alert("Text: " + $("#test").text());
• set
$("#test1").text("Hello world!");
html()
• html() sets or returns the content of a particular element
• get
alert("HTML: " + $("#test").html());
• set
$("#test2").html("<b>Hello world!</b>");
val()
• val() sets or returns the value of a form element
• get
alert("Value: " + $("#test").val());
• set
$("#test3").val(“Ken");
attr()
• attr() sets or returns the attribute of a particular element
• get
alert($("#kc").attr("href"));
• set
$("#w3s").attr({
"href" : "http://www.cmu.ac.th/",
"title" : "CMU"
});
Adding & Removing
• jQuery also lets us add and remove elements from the DOM
• Adding
• append()
• prepend()
• after()
• before()
• Removing
• remove()
• empty()
Adding
• append()
• Inserts content at the end of the selected element
• prepend()
• Inserts content at the beginning of the selected element
• after()
• Inserts content after the selected element
• before()
• Inserts content before the selected element
Removing
• remove()
• removes the selected element and its children
• empty()
• removes the children of the selected element
• We can filter elements,
• i.e. the remove function takes 1 parameter which could remove elements of a certain type within the selected element
CSS
• jQuery can also manipulate css styles (as we have already seen in some examples)
• addClass()
• removeClass()
• css()
CSS
• Remember CSS is for layout as well as style!
• jQuery gives us ways of manipulating the dimensions of elements
• width() – sets or returns
• height() – sets or returns
• innerWidth() - returns
• innerHeight() - returns
• outerWidth() - returns
• outerHeight() - returns
DOM Traversal
• Each element in the DOM could be a parent, a child or a sibling
• jQuery gives us ways of moving through the DOM to find (select) a particular element
• we can move UP to a parent
• we can move DOWN to a child
• we can move ACROSS to a sibling
Traversing UP
• Three useful functions
• parent() – allows us to move up a level
$("span").parent();
• parents() – selects every element between this node and the root
$("span").parents();
$("span").parents("ul");
• parentsUntil() – selects every element between this node and a specified element
$("span").parentsUntil("div");
Traversing DOWN
• 2 Useful functions
• children()
• returns all direct children of the element
$("div").children();
$("div").children("p.1");
• find()
• returns all children down to the bottom
$("div").find("span");
$("div").find("*");
Traversing Across
• 7 Useful functions
• siblings()
• next()
• nextAll()
• nextUntil()
• prev()
• prevAll()
• prevUntil()
Filtering
• Filtering helps us with traversal by helping to find a particular element
• first()
• last()
• eq()
• filter()
• not()
AJAX
• Asynchronous Javascript and XML
• AJAX is AWESOME!
• AJAX allows us to exchange data with the server and update parts of a page, without needing to reload it.
load()
• load() loads data from the server that can be put into a page.
$(selector).load(URL, data, callback);
• data is optional parameters to send to the function as key:value pairs