Objects and Animations


Goal

By the end of today, you will be able to:

  1. Understand how to create and use JS Object Literals.
  2. Understand how JS animations work and how to use the .animate() method.
  3. Create a cool sliding slideshow.

Recap

We learned about JS Object Literals and animated slideshows. We'll talk about animation a bit later.

JS Objects and Object Literals

  • A data structure for multiple values: a set of properties and values.
  • The values can be any datatype (strings, numbers, booleans, dates)
  • The values are accessed by their property name: fred.age
  • Property names obey the rules of JS variables. (Though you can have other names using a different syntax; we won't do this.)

Quiz Nr. 1

Suppose we want to define an object to represent Ron. Which is correct:

  1. ron = {age: 17, hair color: red};
  2. var ron = [age: 17, hair_color: red];
  3. var ron = { age: 17; hair_color: "red"};
  4. var ron = { age: 17, hair_color: "red"};

Quiz Nr. 2

What's the syntax error in the following object creation?

var ron = { age: 17, hair color: red };
  1. red should be in quotation marks

  2. uses var when it shouldn't

  3. commas between pairs should be a semi-colon

  4. invalid property name

Quiz Nr. 3

Suppose we want change his age to 18. Which is correct:

  1. ron.age = 18;
  2. ron[age] = 18;
  3. ron.age++;
  4. ron.setAge(18);

Animations

jQuery animations are easy to do, but very limited. The syntax:

$(sel).animate(js_object, duration);

Some details:

  • The duration is in milliseconds. So, supplying 1000 means the animation will take place over one second. 1500 is one and a half seconds, while 500 is half a second. The larger the number, the slower the animation, which is sometimes surprising at first.
  • The duration is actually optional; the default value is 400 milliseconds.
  • The CSS properties have to be single numbers, so that they can be smoothly changed over time. For example, the width of an element can easily be changed gradually over time. That is, if the current width is 0px and the target is 500px and the duration is 500 milliseconds, then every 50 milliseconds, the width might go up by 50 pixels:
    50, 100, 150, 200, 250, 300, 350, 400, 450, 500
  • Because the CSS properties have to be single numbers, you can't animate discrete changes like changing from "font-family:Times" to font-family:Verdana" For that reason, you can't change colors using animation (unless you load the jQuery.Color() plugin).
  • The set of CSS properties is given using a JavaScript object, typically using the object literal notation, though if we happen to have a variable that contains a set of CSS property-value pairs, we could use it.

jQuery Effects Examples

A lot of cool effects can be built on top of the basic animation idea. jQuery has methods to have something (an element on the page) fadeOut, fadeIn, slideUp, slideDown, and much more.

Here's a page that demonstrates some jQuery effects. None of these require more than a line of code.

Note that you can combine these with other techniques we've learned. For example, you can have a drop-down menu slideDown or you can have a gallery image fadeIn. Your madlib could have the story slideDown. Be creative!

Exercise: Writing a Animation

As you know, we can even chain several animations together. In the example below, we have an animation that enlarges this box and thickens the border.

#box1

Write some jQuery animation code to animate the box shrinking back to its original state, but twice as fast as the enlargement.

Your solution might look like this:

var large = {width: "500px", height: "100px", "border-width": "4px"};
var small = {width: "0px", height: "50px", "border-width": "2px"};
$("#box1")
    .css(small)          // instantly to this state
    .animate(large,1500)
    .animate(small,750);
  

Did you think of using the JS variable that holds the initial state object?

Animations as Click Handlers

When you ask jQuery to modify a set of things, it will modify each one in the set. This makes it really easy to add the same function as an event handler to lots of different elements, just by using a CSS selector that matches more than one thing. In the following example, we have three boxes, all with the class alice, and we want them to grow by 50px each time you click on them. Try it! (I wanted to use AliceBlue as the background color, but it's too pale.)

I'm Alice 1
I'm Alice 2
I'm Alice 3

The jQuery code to do that is here. Note the use of this to grow only the element that was clicked on, not all three Alices.







Applying Handlers to Multiple Elements

Here we have a list of Hagrid's Horribles. It's a simple ordered list (OL), and the ID is hagrids.

  1. Fluffy
  2. Norbert
  3. Aragog
  4. Buckbeak
  5. Blast-ended Skrewts

Define a function named engorgio that increases the font size of an element by 10px. Attach that function as an event handler for click events to all the elements of the list, and then try it out. Clicking on one item in the list should increase by 10px the font size of that element only, and none of the others.

(It might be less frightening to define reductio, but harder to see.)


Your solution might look like this:

function engorgio() {
    var bigger = 10 + parseInt($(this).css("font-size"));
    $(this).animate({"font-size": bigger+"px"});
}

$("#hagrids li").click(engorgio);
  

Slideshows

Below is a variation on the final sliding slideshow we saw in the reading. Jump down and look at it, and then come back and read through the code.

Slideshow HTML

Here's the HTML. Pretty simple, so far. We added a couple of buttons.



Slideshow CSS

Here's the CSS. This is pretty tricky!



Slideshow JS

Here's the JS. Tricky, but not very tricky.



We made a few small changes from the reading:

  • We packaged up the code into nice neat functions.
  • We added one of the functions as an event handler for one of the buttons.

Here it is in action:

  • Harry Potter
  • Ron Weasley
  • Hermione Granger
  • Draco Malfoy

Exercise: Previous Slide

Write some JS code to implement the previous slide button. Try it out here:


Your solution might look like this:

function prevSlide() {
    currentSlideIndex--;
    if( currentSlideIndex < 0 ) {
        currentSlideIndex = $("#slides4 li").length - 1;
    }                            
    displaySlide();
}

$("#prevSlideButton").click(prevSlide);
  

Summary

We hope that after these activities you have a good understanding of:

  • JS object literals and how to use them.
  • Sliding Carousels and how to set them up.

Solutions

Will be posted later, visit again after .

Quiz answers:

1. D
2. D definitely but A might also be true
3. A definitely but C might also be true, if Ron is 17. B is *almost*
correct, but age would be a variable, not a 

© Wellesley College Computer Science Staff. This work is licensed under a Creative Commons License. Date Modified: Friday, 08-Apr-2016 11:10:18 EDT