Learn about...
jQuery/JavaScript implements the behavioral layer of a web page and works together with the structural layer (HTML) and presentational layer (CSS). jQuery uses CSS-like syntax to select HTML elements so they can be altered and animated based on user interaction with the web page. This is all done inside the web browser (client-side), which allows web pages to be very dynamic without having to make HTTP requests.
None
Download the compressed jQuery library, saved it as jquery.js, and save it in your lab10 folder.
jQuery is simply a JavaScript library.
It is included using a script
tag, which
can go anywhere in an HTML document. See below:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Demo</title>
</head>
<body>
<script src="jquery.js"></script>
<script>
// Insert a jQuery Ready Event
</script>
</body>
</html>
To ensure that JavaScript code runs after the browser finishes loading the entire document, jQuery has a method (i.e., function) known as the ready event, which executes when the DOM is fully loaded:
$( document ).ready(function() {
// Code that you need executed when the page is loaded.
// Insert some jQuery Event Handlers
});
Most jQuery code is executed when a user performs some event, e.g., click a button, move the mouse, drag and drop, etc.
$( "button" ).click(function() { alert( "You just clicked a button" ); });
$( query )
is the powerful jQuery selector. If the query
is a string
jQuery will interpret the string as a CSS-like pattern and search the DOM for all the elements that match the pattern.
Here are some examples of css-like queries:
$("p")
- Get all the paragraph elements.$("nav a")
- Get all the a
elements that are inside of nav
elements.$(".menu")
- Get all the HTML elements where the class name is "menu"$("#intro")
- Get the single HTML element with the id name "intro"Here are some more advance queries:
$("li:eq(2)")
- Get the third li
element on the page (index starts at zero). This selects one element.$(":button")
- Get all the buttons. Specifically, both <button>
and <input type="button">
$("input[type='radio']")
- Get all the input
elements that are of type "radio"$("[style='color: red']")
- Get any HTML element where the style attribute equals "color: red"$("tr:first")
- Get the first tr
element on a page.$("select option:selected")
- Get the selected option from a select
menu.$("li:nth-child(2)")
- Get the second child li
element in each list. (index starts at one). If there were four lists this would select the second li
in each of the four lists.h2
element with
class="important"
will display the alert
"This is an important h2" if the h2
is clicked.li
element on the page will be changed to have orange text, i.e., $( query ).css("color", "orange").eq
function; search the reference page for a function that will always find the last element.
jQuery can apply many different effects to HTML elements. These effects include: show, hide, fadeIn, fadeOut, slideDown, slideUp, etc.
div
, make the first button
fade out (.fadeOut("slow")).div
, make the first button fade
in (.fadeIn("slow")).div
up and down (see the slideToggle reference).jQuery includes a very powerful method called animate that creates animation effects by gradually changing an HTML element's properties (position, height, width, font size, border, opacity, etc.).
$("the_element").animate({property: value, property: value, ...}, duration)
In the example above, we can change one or more of the elements properties. Duration is the total animation time measured in milliseconds (1000 milliseconds = 1 second).
fontSize
to "20px"borderWidth
to "5px"backgroundColor
to "red"body
until all the
components in the head
are fully loaded, but this really depends on the browser's implementation.
Thus, it is always recommended to encapsulate JavaScript/jQuery code inside the ready function.div
up and down. Use appropriate id names.div
up (-=50px) and down (+=50px) by
changing the top
property.
jQuery animations use a "swing" effect where the motion speeds up in the beginning and then slows down at the end. However, you can override the "swing" effect to "linear" movement or a variety of "easing" effects. Also, animations calls can be sequenced together, i.e.,
$(element).animation().animation().animation()
to create a chain of effects. By default, each animation effect is placed in a queue and executed in order. However, you can override the queue and force animations to execute in parallel.
queue: false
to queue: true
for the width and height effect.easing:"swing"
to easing:"easeOutBounce"
for the width and height effect.easing:"swing"
to easing:"linear"
for the backgroundColor effect.While sequencing animation calls ( $(element).animate().animate() ) can queue up multiple effects for a single HTML element, this technique cannot be used to sequence effects for different elements. This is because each element must be selected to be animated. To sequence effects for different elements, we use a more advanced animate method that takes several parameters.
$("the_element").animate(properties, duration, easing, complete)
In the code above, complete is function call or function definition. This function will be executed after the animation is complete.
The animation of two or more elements can be sequenced by nesting animation calls as follows:
$("element1").animate(p, d, e, function () { $("element2").animate(p, d, e, function () { $("element3").animate(p, d, e); }); });
In the code above, p is the list of properties to animate, d is the duration of the animation, and e is the "easing" algorithm that is used.
fontSize: "30px"
to the list of animated properties for blocks 1, 2, and 3.div
with id="block4" and add the following
effect: $( "#block4" ).animate({width: "400px", color: "white", fontSize: "30px" }, 2000, "easeInBounce");This effect should be nested inside of block3. Thus, block4 should be animated after block3 is finished.
JavaScript (remember jQuery is just a special JavaScript library) implements the behavioral layer of a web page and works together with the structural layer (HTML) and presentational layer (CSS). In this part, we are going to start with basic HTML, add CSS, and then add jQuery to better show the role of each layer (structural, presentational, and behavioral).
body { text-align: center; background: black } #wrapper{ margin:0px auto; width:700px; }Refresh the page in Chrome and notice that we make the background black and make the wrapper centered with a width of 700px.
#content{ position:relative; width:700px; height:300px; top:30px; background: url('images/background.jpg'); }Refresh the page in Chrome and notice that we have now defined the content area to be a 700 x 300 block with a background image.
#sun { position:absolute; top:10px; left:30px; z-index:1 } #cloud1 { position:absolute; top:40px; left:-200px; z-index:2; } #cloud2 { position:absolute; top:60px; left:-200px; z-index:3; } #raft { position:absolute; top:220px; left:312px; z-index:2; } #ripple { position:absolute; top:220px; left:309px; z-index:1; } #text { position:absolute; top:-50px; left:200px; z-index:2; } #stamp { position:absolute; top:5px; left:801px; z-index:4; }Refresh the page in Chrome and notice that we have positioned each HTML element.
z-index
is used to specify the ordering of layers;
z-index: 2
will float in front of z-index: 1
.
Also, even though we are using absolute positioning, these elements are
all inside of #content, so the absolute position is actually relative to
the position of #content.
Note: Compared to other programming languages like Java and C++,
this code is quite minimal to setup an animation area with seven objects.
$(document).ready(function() { setTimeout("animation()",1000); }); function animation(){ $("#text").animate({top: '80px' }, 2000, 'easeOutBounce'); $("#stamp").animate({left: '595px' }, 2000, 'easeOutBounce'); }Refresh the page in Chrome and notice that after a 1000 millisecond pause, the #text and #stamp elements are animated. After the web page is fully loaded (ready event), we use
setTimeout
to create a 1-second delay before calling a function named
animation
.
function animation(){ sun_raft(); $("#text").animate({top: '80px' }, {duration:2000, easing:'easeOutBounce'}); $("#stamp").animate({left: '595px' }, {duration:2000, easing:'easeOutBounce'}); } function sun_raft(){ $("#sun").animate({opacity:"0.5"},1000).animate({opacity:"1.0"},1000); $("#raft").animate({top:"-=5px"},1000).animate({top:"+=5px"}, 1000); setTimeout("sun_raft()",2000); }Refresh the page in Chrome and notice that the #sun and #raft are now animated.
function animation(){ sun_raft(); $("#text").animate({top: '80px' }, {duration:2000, easing:'easeOutBounce'}); $("#stamp").animate({left: '595px' }, {duration:2000, easing:'easeOutBounce'}); setTimeout("cloud1()",1000); } function cloud1(){ $("#cloud1").animate({left:"+=900px"},10000).animate({left:"-200px"}, 0); setTimeout("cloud1()",11000); }Refresh the page in Chrome and notice that #cloud1 is now animated. It moves from its initial position, which is -200px from #content left border, to 900px from #content's left border. The duration of this first move is 10 seconds. Then, it moves it back to its initial position in zero second. Finally, we recursively call the function again after an 11 second delay to create an animation loop.
overflow:hidden;
to the CSS for #content, which will
hide the elements if they are outside of the #content area.