In this article we look at the basics of how to manipulate CSS styles using JavaScript.
Information: JavaScriptJavaScript 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:
Make a new HTML document, doc5.html
. Copy and paste the content from here, making sure that you scroll to get all of it:
<!DOCTYPE html>
<html>
<head>
<title>Mozilla CSS Getting Started - JavaScript demonstration</title>
<link rel="stylesheet" type="text/css" href="style5.css" />
<script type="text/javascript" src="script5.js"></script>
</head>
<body>
<h1>JavaScript sample</h1>
<div id="square"></div>
<button type="button" id="clickMe">Click Me</button>
</body>
</html>
Make a new CSS file, style5.css
. Copy and paste the content from here:
#square {
width: 20em;
height: 20em;
border: 2px inset gray;
margin-bottom: 1em;
}
button {
padding: .5em 2em;
}
Make a new text file, script5.js
. Copy and paste the content from here:
var square = document.getElementById("square"),
clickMe = document.getElementById('clickMe');
function doDemo () {
var button = this;
square.style.backgroundColor = "#fa4";
button.setAttribute("disabled", "true");
setTimeout(clearDemo, 2000, button);
}
function clearDemo (button) {
var square = document.getElementById("square");
square.style.backgroundColor = "transparent";
button.removeAttribute("disabled");
}
clickMe.onclick = doDemo;
Open the document in your browser and press the button.
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:
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
.backgroundColor
corresponds to the CSS property background-color
. JavaScript does not allow hyphens in names, so “camelCase” is used instead.button
that changes the button’s appearance when it is disabled.Change the script so that the square jumps to the right by 20 em when its color changes, and jumps back afterwards.
AttributionsThis 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
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4