Manipulating CSS with JavaScript

Summary

In this article we look at the basics of how to manipulate CSS styles using JavaScript.

Information: JavaScript

JavaScript is a programming language. JavaScript is widely used to provide interactivity in web sites and applications. JavaScript can interact with stylesheets, allowing you to write programs that change a document’s style dynamically.

There are three ways to do this:

By working with the document’s list of stylesheets—for example: adding, removing or modifying a stylesheet.

By working with the rules in a stylesheet—for example: adding, removing or modifying a rule.

By working with an individual element in the DOM—modifying its style independently of the document’s stylesheets

Action: A JavaScript demonstration

Make a new HTML document, doc5.html. Copy and paste the content from here, making sure that you scroll to get all of it:

What this code does, is that it changes the background color of the #square to #ffaa44. Here’s a JSFiddle so you can see it working live.

Notes on what is happening in the above example:

The HTML document links the stylesheet as usual, and it also links the script.

The script works with individual elements in the DOM. It modifies the square’s style directly. It modifies the button’s style indirectly by changing an attribute.

In JavaScript, document.getElementById("square") is similar in function to to the CSS selector #square and in a similar way, document.getElementById('clickMe') is similar to #clickMe.

In JavaScript, backgroundColor corresponds to the CSS property background-color. JavaScript does not allow hyphens in names, so “camelCase” is used instead.

Your browser has a built-in CSS rule for button that changes the button’s appearance when it is disabled.

See also

Exercise question

Change the script so that the square jumps to the right by 20 em when its color changes, and jumps back afterwards.

Attributions

This article contains content originally from external sources, including ones licensed under the CC-BY-SA license.

Portions of this content copyright 2012 Mozilla Contributors. This article contains work licensed under the Creative Commons Attribution-Sharealike License v2.5 or later. The original work is available at Mozilla Developer Network: Article