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

Get JavaScript For Kids For Dummies now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.