Chapter 7

Building an Animated Robot

HTML, CSS, and JavaScript are a great team. Each piece works with the other two to make great things happen in web browsers.

In this chapter, we put all the pieces together to make Douglas the JavaScript Robot dance!

image

Changing CSS with JavaScript

Just as you can use JavaScript to change the HTML in a web page, you can also use it to change CSS styles. The process is very similar.

The first step is to select the element you want to apply or change a style on. In Chapter 5, we show you how to do this using getElementById. For example, to select Douglas’s left eye, you can use the following code:

document.getElementById("lefteye")

Once you’ve selected an element, you can change its style by attaching the style property to the selector, followed by the style you want to change. To change the color of the left eye, you can use this JavaScript:

document.getElementById("lefteye").style.backgroundColor = "purple";

Do you notice anything strange about this code, compared to how you changed the background color with CSS? When changing styles with JavaScript, there are two rules:

  • When the CSS property is just one word, such as margin or border, you can use the same CSS name to change the style in JavaScript.
  • If the CSS property has dashes (-), the CSS property name gets converted to camelCase. So, background-color gets changed to backgroundColor.

Here are some examples of CSS properties, and how each property is spelled in JavaScript:

CSS Property

JavaScript Style Property

background-color

backgroundColor

border-radius

borderRadius

font-family

fontFamily

margin

margin

font-size

fontSize

border-width

borderWidth

text-align

textAlign

color

color

remember JavaScript cares a lot about capitalization. The capital letters in the JavaScript style properties need to be there in order for the properties to work.

Modifying Douglas with JavaScript

Modifying CSS using JavaScript makes it possible for the look and position of elements to change in response to user input.

We’ll make Douglas dance in a little bit, but let’s get some practice with making changes to him first:

  1. Go to the public dashboard at http://jsfiddle.net/user/forkids/fiddles, find the program called Chapter 7: Start, and open it.

    You see the Douglas Robot project pretty much as we left it at the end of Chapter 6, as shown in Figure 7-1.

  2. Click the Fork button to create a copy of this program in your own JSFiddle account.
  3. Type the following into the JavaScript pane to change Douglas’s left eye color:

    document.getElementById("lefteye").style.backgroundColor = "purple";

  4. Click Run to see the result.

    Douglas’s left eye will change to purple, as shown in Figure 7-2.

  5. Press Return (Mac) or Enter (Windows) to start a new line in the JavaScript panel and then type the following:

    document.getElementById("head").style.transform = "rotate(15deg)";

  6. Click Run to see the result.

    Douglas now is tilting his head to his left. He looks ready to dance (see Figure 7-3)!

  7. Open the Fiddle Options in the left menu and give your program a new name.
  8. Click Update and then click Set as Base to save your program to your public dashboard.
image

Figure 7-1: Douglas, the unanimated JavaScript robot.

image

Figure 7-2: Douglas’s left eye is now purple.

image

Figure 7-3: Douglas is ready to dance!

Experimenting with Douglas

There are countless possibilities for customizing Douglas using JavaScript’s style properties. To get started experimenting with a few, try adding each of the following statements to the JavaScript pane and then running them:

// Put a 2-pixel-wide, solid black border around his body.

document.getElementById("body").style.border = "2px black solid";

// Round the corners of his mouth.

document.getElementById("mouth").style.borderRadius = "4px";

// Put yellow dots around his right eye.

document.getElementById("righteye").style.border = "4px yellow dotted";

// Change his left arm's color.

document.getElementById("leftarm").style.backgroundColor = "#FF00FF";

// Change the text color.

document.getElementById("body").style.color = "#FF0000";

// Give Douglas hair.

document.getElementById("head").style.borderTop = "5px black solid";

Now it’s your turn. Can you figure out how to make each of the following changes using JavaScript?

  • Tilt Douglas’s head to the other side.
  • Make Douglas’s nose round.
  • Make Douglas’s right arm green.
  • Make Douglas’s lips pink.

If you need help with any of these, visit our public dashboard on JSFiddle and look for the program named Chapter 7: Changing CSS with JS.

warning Keep in mind that JavaScript is very sensitive. If you have a typo, or forget a period, or spell getElementById wrong anywhere in the JavaScript pane, all the lines of JavaScript will fail to run, not just the statement where you made the mistake.

Make Douglas Dance!

Now that you know how to change CSS using JavaScript, let’s put that knowledge to good use and make Douglas more animated!

  1. With the latest version of your Robot Style program open in JSFiddle (or the Chapter 7: Start fiddle from our public dashboard), press the Fork button in JSFiddle.
  2. Open Fiddle Options in the left menu and change the name of the fiddle to Animated Robot.
  3. Click Update to save your work.

    Now you have a new fiddle for the new and improved dancing Douglas, and you can still get to the previous, nondancing, Douglas from your public dashboard.

Douglas isn’t the greatest dancer, but he does have a few moves that he’s very proud of. The first is one he calls the “eye bounce.” His eye makes a quick movement upward and then floats back into place. Trust us, when he does it to the beat, it’s almost hypnotic.

Figure 7-4 shows Douglas in the middle of one of his signature eye bounces.

image

Figure 7-4: Douglas doing the eye bounce.

In our program, you’re going to control Douglas’s dancing by clicking his different parts to animate them. We start with programming his right eye to bounce when you click it.

  1. In the JavaScript pane, type the following statement:

    var rightEye = document.getElementById("righteye");

    This variable declaration creates a shortcut for us to refer to the right eye. Now that this has been created, every time you need to refer to Douglas’s right eye in the rest of the program, you can just use the variable named rightEye.

  2. Tell JavaScript to listen for mouse clicks on the right eye with this statement:

    rightEye.addEventListener("click", moveUpDown);

Handling events

Event listeners are a way to tell JavaScript to watch an element for something to happen to it, and then to do something (handle it) when the event happens.

In JavaScript, we use a method called addEventListener to tell programs what to do when events happen. To listen for and handle events, you need three parts:

  • The event: Whenever something happens in a web browser, it’s called an event. Examples of events include clicking the mouse, pressing a key, dragging and dropping, hovering your mouse over something, and selecting text.

    Events aren’t just the things that people do with web browsers. Other events happen without your doing anything at all. These include the page loading, elements displaying, errors happening in the code, and animations completing. Here are the most common events that happen in a web browser.

    • click: The user clicks the mouse.
    • submit: A form is submitted.
    • drag: An element is being dragged.
    • drop: An element has been dropped after being dragged.
    • copy: The user has copied content.
    • paste: The user pastes content.
    • mouseover: The mouse passes over an element.
    • load: The page loads.

    To listen for events, put the name of the event you want to listen for in quotes inside the addEventListener method. For example:

    target.addEventListener("click", listener)

  • The event target: The next step in creating an event handler is to attach the addEventListener method to an object. For example, to listen for the click event on Douglas’s right eye, you would use the following:

    rightEye.addEventListener("click", listener);

    The element that JavaScript will listen for events on is called the event target. In this case, rightEye (which is a variable you created to stand for the value document.getElementById("righteye") is the event target.

  • The listener: The third part of an addEventListener statement is the actual listener. This is the object that should be notified when the event happens.

    In the case of Douglas, we want to notify a function that we’re going to write and that we’re going to call moveUpDown. This function will serve the purpose of moving Douglas’s eye up and down.

    rightEye.addEventListener("click", moveUpDown);

The format of a typical event handler is as follows:

target.addEventListener("event", listener);

Now that you know how addEventListener works, let’s get back to Douglas the JavaScript Robot and create the listener that we want to activate when someone clicks his eye.

Writing a listener

So far, the JavaScript pane should contain the following code:

var rightEye = document.getElementById("righteye");

rightEye.addEventListener("click", moveUpDown);

If you run your program now, you’ll find that it doesn’t do anything at all. That’s because we haven’t yet created the listener.

A listener is a function, or a smaller program within the larger JavaScript program. Whenever the event happens that the listener is attached to, the listener function runs.

The listener for the eye bounce animation will be called moveUpDown. Follow these steps to create the moveUpDown listener function.

  1. After the last line of code in the JavaScript pane, press Return or Enter a couple times to insert some white space.
  2. Type the following to start creating the listener:

    function moveUpDown(e) {

    This code starts your function and gives it a name. Note the e between the parentheses. When the function is called by the addEventListener function, the e will contain some information about the event that just happened, which we can use inside of the function. More on this in a moment!

  3. Press Return or Enter after the open curly bracket ({) and type the rest of the function:

    var robotPart = e.target;

    var top = 0;

    var id = setInterval(frame, 10) // draw every 10ms

      function frame() {

        robotPart.style.top = top + '%';

        top++;

        if (top === 20){

          clearInterval(id);

        }

      }

    }

    This may look complicated, but it’s actually fairly simple. Before we explain, let’s test it out to make sure it works.

  4. Click Run.

    If you entered everything correctly, you should now be able to click Douglas’s right eye and see it bounce, as shown in Figure 7-5.

image

Figure 7-5: Click Douglas’s eye to make it bounce.

If your program isn’t working correctly, double-check your code. It should be exactly the same as Listing 7-1.

Listing 7-1 The Code Required in the JavaScript Pane to Enable the Eye Bounce

var rightEye = document.getElementById("righteye");

rightEye.addEventListener("click", moveUpDown);

function moveUpDown(e) {

  var robotPart = e.target;

  var top = 0;

  var id = setInterval(frame, 10) // draw every 10ms

   function frame() {

    robotPart.style.top = top + '%';

    top++;

    if (top === 20){

      clearInterval(id);

    }

  }

}

If you entered everything correctly and Douglas’s eye does the bounce when you click it, read on to find out how it all works!

Creating animations with JavaScript

Computer animation, like film and video animation, is a trick. The trick relies on showing a series of pictures in a quick enough succession that the images appear to move.

Each picture in an animation is called a frame. The way Douglas’s eye bounce animation works is that it shows his eye in a slightly different place, every 10 milliseconds (one-tenth of a second), starting with the position of the eye being at the top of the head, and ending with it at 20 percent from the top of the head.

Figure 7-6 shows the position of the eye at various points during the animation.

image

Figure 7-6: Douglas’s eye at various points in the animation.

Now let’s step through the code and see how this effect is created in JavaScript. We’ll start with the first line after the function declaration:

var robotPart = e.target;

This statement uses the event object (that comes automatically from the addEventListener method) to find out what part of the robot (what element) was clicked on. It stores the information about that element (the rightEye in this case) in a new variable called robotPart.

This statement creates a new variable called top and gives it a value of 0:

var top = 0;

This top variable is what we’ll use to position the eye in each frame of the animation.

The following line uses a command called setInterval to make the animation magic happen:

var id = setInterval(frame, 10); // draw every 10ms

The setInterval command will run the function listed first in the parentheses, and will do it on a schedule determined by the number in the parentheses.

The number is a number of milliseconds (thousandths of a second) to wait before doing the thing again. So, 1,000 milliseconds equal a second. The larger this number is, the slower the animation will go, and vice versa.

Here we’re creating a new function (or mini-program) that is run by the setInterval command and that will handle the task of creating each new animation frame:

function frame() {

Here, we set the value of top to the value of our top variable and add % at the end, for the element that was clicked:

robotPart.style.top = top + '%';

So, when you first click the eye, top will be set to 0 percent, which will put it at the very top of Douglas’s head.

The following line increases the value of top by 1 using a thing called the increment operator:

top++;

We cover the increment operator in more detail in Chapter 9.

Here, we check whether the final frame of the animation has been reached, by seeing if top is equal to 20:

if (top === 20){

If top is equal to 20, the next command is run.

The clearInterval statement ends the animation:

clearInterval(id);

Finally, we just clean everything up by closing all the curly brackets that we opened:

    }

  }

}

Animating another element

Now that we’ve written the moveUpDown function to animate one eye, animating the other eye is a simple matter of adding another event listener.

  1. Click Update to save your work so far.
  2. Insert the following new variable declaration just below the one for rightEye:

    var leftEye = document.getElementById("lefteye");

  3. Insert the following new event handler just below the rightEye one:

    leftEye.addEventListener("click", moveUpDown);

  4. Click Run.

    Now, clicking either the left or right eye will cause the moveUpDown animation to happen on the clicked element.

Adding a second animation function

Douglas isn’t a one-trick robot. He has at least one more dance move besides the eye bounce. He calls this one the “arm sweep.” This classic move involves a smooth movement of the left arm from right to left across Douglas’s body as his eyes stare straight ahead.

To create the arm sweep animation, we’ll add a second listener function, based on the moveUpDown function, but we’ll modify it slightly in order to animate the arm from right to left rather than from top to bottom.

  1. Create a new variable, just under the two other variables, to represent the left arm:

    var leftArm = document.getElementById("leftarm");

  2. Write a new event handler, underneath the two other event handlers.

    leftArm.addEventListener("click", moveRightLeft);

  3. Select the moveUpDown function and press maccmd +C (Mac) or Ctrl+C (Windows) to copy it.

  4. Paste a copy of the moveUpDown function below the existing moveUpDown function.

Now, we’ll modify the copy of moveUpDown() to create the new moveRightLeft function.

  1. Change the name of the function from moveUpDown to moveRightLeft.

    function moveRightLeft(e) {

  2. Change the second line in the function body to the following:

    var left = 0;

  3. Change the first line inside of the frame function to the following:

    robotPart.style.left = left + '%';

  4. Change the second line of the frame function to the following:

    left++:

  5. Change the third line of the frame function to the following:

    if (left === 70){

When you’re finished with the changes, your new moveRightLeft function should match the following code in Listing 7-2.

Listing 7-2 The Finished moveRightLeft Function

function moveRightLeft(e) {

  var robotPart = e.target;

  var left = 0;

  var id = setInterval(frame, 10) // draw every 10ms

  function frame() {

    robotPart.style.left = left + '%';

    left++;

    if (left === 70){

      clearInterval(id);

    }

  }

}

To save your work and test out the new animation, press Update. When you click Douglas’s left arm now, you’ll see the moveRightLeft animation work, as shown in Figure 7-7.

image

Figure 7-7: Douglas performs the arm sweep move.

The completed code in the JavaScript pane should now match Listing 7-3.

Listing 7-3 The JavaScript Required to Implement Both of Douglas’s Dance Moves

var rightEye = document.getElementById("righteye");

var leftEye = document.getElementById("lefteye");

var leftArm = document.getElementById("leftarm");

rightEye.addEventListener("click", moveUpDown);

leftEye.addEventListener("click", moveUpDown);

leftArm.addEventListener("click", moveRightLeft);

function moveUpDown(e) {

  var robotPart = e.target;

  var top = 0;

  var id = setInterval(frame, 10) // draw every 10ms

  function frame() {

    robotPart.style.top = top + '%';

    top++;

    if (top === 20){

      clearInterval(id);

    }

  }

}

function moveRightLeft(e) {

  var robotPart = e.target;

  var left = 0;

  var id = setInterval(frame, 10) // draw every 10ms

  function frame() {

    robotPart.style.left = left + '%';

    left++;

    if (left === 70){

      clearInterval(id);

    }

  }

}

Now it’s your turn to have some fun making Douglas dance! Start out by turning on some music and clicking his eyes and arm to the beat! Next, try adding some new event handlers to animate different parts of Douglas, such has his nose, his mouth, or his right arm!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset