Changing CSS using JavaScript
by
kirupa | 31 March 2011
Have questions? Discuss this HTML 5 tutorial with
others on the forums.
There will be times when you want to change how your
application look when users are interacting with it. Sure,
you can use CSS pseudo classes, but what if you
want to trigger a visual change on something other than the
handful of cases where pseudo classes would apply?
Fortunately, to address what pseudo classes cannot
do, you can use JavaScript to apply CSS rules to elements to
change their appearance in a whole lot more conditions. For example, let's say I have a
simple page with a button displayed on a gray background:

When the button is clicked, the background is changed
from gray to some magenta/pink color:

The way this change was done was not by setting some
inline style using JavaScript. Instead, while JavaScript is
still used, it is used to swap out one CSS style rule with
another:
- .backgroundOne
{
- background-color:
#333333;
- }
- .backgroundTwo
{
- background-color:
#990033;
- }
The backgroundOne rule corresponds to the gray
background, and the backgroundTwo rule corresponds to the
magenta background. Determining which to apply and actually
applying it was handled entirely by JavaScript! In this
tutorial, you will learn the secrets passed down from my
forefathers on how to do that.
If you
want to follow-along, go ahead and create a new HTML
document and copy/paste the following code into it:
- <!DOCTYPE
html>
- <html
lang="en-us">
-
- <head>
- <meta
charset="utf-8">
- <title>Changing
CSS
Using JavaScript</title>
- <style
type="text/css">
- #mainDiv
{
- text-align:
center;
- padding:
10px;
- border-radius:
3px;
- font-family:
Cambria,
Cochin,
Georgia,
Times,
"Times New Roman",
serif;
- font-size:
xx-large;
- }
- #mainDiv
p {
- color:
#FFFFFF;
- border-radius:
3px;
- padding:
10px;
- }
- #mainDiv
button
{
- background-color:
#CC3300;
- font-size:
small;
- font-weight:
bold;
- font-family:
Georgia,
"Times New Roman",
Times,
serif;
- color:
#FFFFFF;
- }
- .backgroundOne
{
- background-color:
#333333;
- }
- .backgroundTwo
{
- background-color:
#990033;
- }
-
- </style>
- </head>
-
- <body>
- <div
id="mainDiv"
class="backgroundOne">
- <p>I
am so
bored...</p>
- <button
id="clickButton">click
me</button>
- </div>
-
- <script>
- var
myButton
=
document.getElementById("clickButton");
- var
myDiv
= document.getElementById("mainDiv");
-
- myButton.addEventListener('click',
doSomething,
false);
-
- function
doSomething()
{
-
- }
-
- </script>
- </body>
-
- </html>
When you preview this HTML in your browser, you will
basically see something that looks as follows:

I am not going to go over the HTML or the CSS that exists
in great detail, for it should be straightforward. What I
will want you to focus on is the JavaScript:
- <script>
- var
myButton
=
document.getElementById("clickButton");
- var
myDiv
= document.getElementById("mainDiv");
-
- myButton.addEventListener('click',
doSomething,
false);
-
- function
doSomething()
{
-
- }
-
- </script>
The myButton and
myDiv variables, respectively, get
a reference to the button and div elements that live in our
HTML. You can learn more on that by reading the
Referencing HTML Elements using JavaScript tutorial.
The other important code deals with reacting to our
button click. When our button is clicked, the
doSomething function gets
called. It is inside this function where everything we do
will live.
The easiest and most direct way to change your CSS via
JavaScript is to set the className
property on an element to the class selector whose CSS rule
you wish to apply. In our case, that would be
backgroundTwo:
- myDiv.className
=
"backgroundTwo";
Your full script would look as follows:
- <script>
- var
myButton
=
document.getElementById("clickButton");
- var
myDiv
= document.getElementById("mainDiv");
-
- myButton.addEventListener('click',
doSomething,
false);
-
- function
doSomething()
{
- myDiv.className
=
"backgroundTwo";
- }
-
- </script>
When you preview your application, you will see that your
div's background changes to the color specified by the
backgroundTwo rule when your button is clicked. Wohoo!
While the approach described here works most of the time,
there is one side-effect. If your element already has some
CSS rules based on a class selector affecting it, this
approach obliterates those with the new
class selector you specify. Talk about disrespecting the
local culture!
To avoid that, use the following approach where you add
your new class selector to the element without getting rid
of any class selectors that may already exist:
- myDiv.className
+=
"backgroundTwo";
The main change is that the destructive
= has been changed to the
additive +=. To remove a CSS
selector that has been applied to your element, you have two
ways of handling this as well. One way is by just setting
the className to an empty string:
- myDiv.className
= '';
This approach is OK if you want to clear all of your
selectors, but if you want to only remove a particular
selector, the second approach may work better. To only
remove the class selector you are interested in while
keeping the other selectors intact, use the following
approach instead:
- myDiv.className
=
myDiv.className.replace("backgroundTwo",'');
What you are doing is calling the
replace function on
className to find the string
representing the class selector you wish to replace (backgroundTwo)
and replace it with a blank space ('
'). In fact, this approach works even in cases where
you may only have one class selector specified in your
className property. This code will find that one property
and replace it with an empty string.
I've been very careful about describing
how to work with CSS only if it exists in the markup. One
thing I encourage you to avoid is setting CSS values and
properties directly using JavaScript. The following is an
example of what not to do where I set the background on our
div to the color directly without using a CSS rule:
- myDiv.style.backgroundColor
=
"#990033";
To set the background color, I used the backgroundColor
property. Equivalent properties exist for all of the other
CSS properties you may want to work with.
The reason I discourage this approach is because it makes
your code less maintainable. If you ever decide to change
the color of the background when the button is clicked, you
will need to ensure that any locations in code are updated
as well. If you just set the appropriate selector name
instead, you can be assured that updating the value in your
CSS rule will ensure that any code that references it will
get the updated value from your CSS without you having to
manually do anything extra.
Well, that's
all there is to mixing JavaScript and CSS as part of a
nutritious application. I presented several ways of both
setting a selector as well as removing it, so be sure to use
the one that is most appropriate. If you are unsure which
approach to take, just use the more general approach for
adding a selector:
- myDiv.className
+=
"backgroundTwo";
Also, use the more general approach for removing a
selector:
- myDiv.className
=
myDiv.className.replace("backgroundTwo",'');
Just like buying a black colored Ford Model T, you can't
go wrong with these two approaches.
You can see a
live version of the example I took screenshots from. My
example has a slight variation to the code you saw presented
here because I wanted to enable toggling the background each
time you clicked on the button.
Need Help?
If you have questions, need some assistance on this topic, or just want to
chat - please drop by our friendly forums
and post your question. There are a lot of knowledgeable and witty people who
would be happy to help you out. Plus, we have a
large collection of smileys
you can use

Share
Did you enjoy reading this and found it useful? If so, please share it with
your friends:
If you didn't like it, I always like to hear how I can do better next time.
Please feel free to contact me directly at kirupa[at]kirupa.com.
Cheers!
|