Lab 10: JavaScript III & jQuery II

Goals

Learn about...

  1. Setting up the jQuery library and where to put your jQuery code.
  2. The importance of the ready event
  3. jQuery Events and Selectors
  4. jQuery Effects and Animations
  5. Easing and Queueing
  6. Sequencing Animations
  7. Putting together HTML, CSS, and jQuery from scratch

Key Concept

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.

Pre-lab Activity

None

In-lab


Part 1: jQuery Setup

jQuery Download Page

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>
Ready Event

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
    
 
});
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.

jQuery Events

$( "button" ).click(function() {

    alert( "You just clicked a button" );

});
jQuery Selectors

$( 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.

jQuery Selectors

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.

Activity 1

  1. Be sure you downloaded the jQuery library and saved it to a file called jquery.js in your lab10 folder.
  2. Download selectors.html to your lab10 folder.
  3. Open the web page in Chrome to see what it looks like.
  4. Open the web page in Notepad++ and view the HTML and jQuery code.
  5. Edit web page to do the following:
    1. Add a selector so that any element with class="important" will display the alert message "this is important" if the element is clicked.
    2. Add a selector so that an h2 element with class="important" will display the alert "This is an important h2" if the h2 is clicked.
    3. Add a selector so that the fifth li element on the page will be changed to have orange text, i.e., $( query ).css("color", "orange").
    4. Add a selector so that the second column of the table will be changed to have a pink background color.
    5. ...any element with an id attribute will be changed to have red text.
    6. ...the odd rows of the table will be changed to have a gray background color. Search the Selector Reference Page for the word "odd".
    7. ...the first four paragraphs will be changed to have blue text (you should do this with one selector). Search the Selector Reference Page for the word "lt".
    8. ...the last element of the unordered list will be changed to have bold text. Do not just count the elements an use the eq function; search the reference page for a function that will always find the last element.
  6. Show the instructor your finished work to get credit for this part

Part 2: jQuery Effects

jQuery can apply many different effects to HTML elements. These effects include: show, hide, fadeIn, fadeOut, slideDown, slideUp, etc.

jQuery Effects

Activity 2

  1. Download effects.html to your lab10 folder.
  2. Open the web page in Chrome and test it to see how it works.
  3. Open the web page in Notepad++ to see the implementation.
  4. Edit effects.html to do the following:
    1. When the mouse goes over (.mouseover) the div, make the first button fade out (.fadeOut("slow")).
    2. When the mouse moves off (.mouseout) the div, make the first button fade in (.fadeIn("slow")).
    3. When the second button is clicked, use slideToggle to slide the div up and down (see the slideToggle reference).
  5. Show the instructor your finished work to get credit for this part

Part 3: jQuery Basic Animation

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.).

Basic Example
$("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).

Activity 3a

  1. Download the jQuery User Interface library, saved it as jquery.ui.js, and save it in your lab10 folder.
  2. Download animate3a.html to your lab10 folder.
  3. Open the web page in Chrome and test it to see how it works.
  4. Open the page in Notepad++ to see the implementation.
  5. Edit the code and animate the following properties:
    1. change the fontSize to "20px"
    2. change the borderWidth to "5px"
    3. change the backgroundColor to "red"
  6. Change the duration of the animation from 2000 milliseconds to 4000.
  7. Note: Sadly there is no official list of properties that can be animated. In general, every CSS property that is numeric can be animated. Sadly, instead of using the CSS property name (font-size), jQuery uses a different name (fontSize). In general, the jQuery property name is the CSS property name with the dash (-) removed wiht the character after the dash capitalized (called "camel case"). Finally, some non-numeric CSS properties (i.e., color and background-color) can be animated, you just have to use the correct jQuery property name (i.e., color and backgroundColor).

Activity 3b

  1. Download animate3b.html to your lab10 folder.
  2. Open the web page in Chrome and test it to see how it works.
  3. Open the web page in Notepad++ to see the implementation.
  4. Note: Notice that I did not include the jQuery ready event. Luckily, this page is so simple that it can load before you can click the buttons. However, if you clicked the button before jquery.js was fully loaded, the jquery code would not work. In general, a web browser will not start rendering the 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.
  5. Edit the code and add the following:
    1. Add two buttons for moving the div up and down. Use appropriate id names.
    2. Add the jQuery selectors and animation method to move the div up (-=50px) and down (+=50px) by changing the top property.
  6. Show the instructor your finished work to get credit for this part

Part 4: Advanced Animation

jQuery Easing and Queuing

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.

  • jQuery Easing - specify the speed at which an animation progresses at different points within the animation.
  • queue: A Boolean value indicating whether to place the animation in the effects queue. If false, the animation will begin immediately, i.e., it will not be put into the queue. If true, it will wait until other effects in the queue have finished.

Activity 4a

  1. Download the jQuery Easing library, saved it as jquery.easing.js, and save it in your lab10 folder.
  2. Download animate4a.html to your lab10 folder.
  3. Open the web page in Chrome and test it to see how it works. Note: There are three animation effects that occur in sequence (width increases, height increases, and color changes).
  4. Open the web page in Notepad++ to see the implementation. Note: The animation effects are sequenced together, i.e., .animate().animate().animate() and are applied to all the HTML elements with the class name "block"
  5. Edit the code and see how the animation changes:
    1. Change queue: false to queue: true for the width and height effect.
    2. Change easing:"swing" to easing:"easeOutBounce" for the width and height effect.
    3. Change the duration to 2000 for both the width and height effect.
    4. Save your code and test your animation to be sure it changed. Take a note of how it changed.
    5. Change easing:"swing" to easing:"linear" for the backgroundColor effect.
    6. Add a fourth animation effect that will change the "borderWidth" to "10px" in just one second; use linear easing and set queue to true.
    7. Save your code and test your animation to be sure it changed. In general, this technique can be used to apply effects with different durations and easing, and to control whether the effects happen in sequence or in parallel. In this case, the width and height effect will start immediately and the color and border effect will happen in sequence.
Sequencing Multiple Elements

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.

Activity 4b

  1. Download animate4b.html to your lab10 folder.
  2. Open the web page in Chrome and test it to see how it works. Note: The three blocks animate in sequence.
  3. Open the web page in Notepad++ to see the implementation. Note: Each animation function has a jQuery selection and animation nested inside of it.
  4. Edit the code and see how the animation changes:
    1. Change block2 from "swing" to "linear" easing.
    2. Change block3 from "swing" to "easeOutElastic"
    3. Add fontSize: "30px" to the list of animated properties for blocks 1, 2, and 3.
    4. In the HTML code right below block3, add a new 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.
  5. Show the instructor your finished work to get credit for this part

Part 5: Three Layer

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).

Activity 5

  1. In your lab10 folder, create a sub-folder called images.
  2. Download each of the following images to the folder you just created, i.e., lab10/images
  3. Download animate5.html to your lab10 folder.
  4. Open the web page in Chrome and check it out. Note: There are six images with no style and no action.
  5. Open the web page in Notepad++ to see the implementation. Note: While the HTML seem useless, it is critically important because it identifies each element and it creates the structure that will be decorated and animated.
  6. Add the following CSS code:
    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.
  7. Add the following CSS code:
    #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.
  8. Add the following CSS code:
    #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.
  9. Add the following JavaScript code:
    $(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.
  10. Add the following JavaScript code shown in bold:
    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.
  11. ON YOU OWN: Add an animation effect for the #ripple that is just like the sun effect, but the opacity should go from 0.1 to 1.0
  12. Add the following JavaScript code shown in bold:
    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.

    Note: JavaScript uses multi-threading so that animations can start executing immediately. Thus, #cloud1 animates while the timeout delay is counting. After the 10 seconds of animation, the timeout only has one second left and then the #cloud1 animation loops again.
  13. ON YOUR OWN: Add an animation effect for #cloud2 that is identical to #cloud1, but the duration should be 7 seconds (faster). Also, inside of the animation function, wait 2 seconds (instead of 1 second) to start the cloud2 animation. This will give cloud1 a head start so cloud2 can pass it.
  14. Finally, add overflow:hidden; to the CSS for #content, which will hide the elements if they are outside of the #content area.
  • Make sure all you work is saved in your lab10 folder. Then, make lab10 into a zipped/compressed file
  • Deliverables

    1. Upload lab10.zip to Blackboard.