August 21, 2010 in Javascript by admin

Have you ever wondered how to use JavaScript to dynamically change your CSS styles on the fly? Changing CSS styles using JavaScript is actually fairly easy and can be used to create wonderful interaction. Since JavaScript and CSS are client-side languages we can easily change these without having to reload the entire page. I will be covering the easiest ways I have found to do this by changing styles on ID elements directly and showing how to change the class of an element.

Here is our HTML for this example:

1
2
3
4
5
<div id='myblock'>
    <a href='#' id='mynav' class='redlink'>my red link</a>
</div>

Here is the CSS we will use for this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#myBlock{
    width: 200px;
    height: 100px;
    background-color: #ffffff;
}
a.redlink{
  color: #CC1100;
}
a.bluelink{
  color: #0099CC;
}

How would we go about changing our CSS with JavaScript? First we will change the heightof our myblock div to 50px from our original 100px. We do this by getting the elements id and setting a new height property.

1
document.getElementById('myblock').style.height = '50px';

To change the background color with JavaScript we would do this by changing the backgroundColor property:

1
document.getElementById('myblock').style.backgroundColor = '#000000';

Now lets say we want to change the class of the redlink to bluelink on the link:

1
document.getElementById('mynav').className = 'bluelink';

That is the easiest way to change CSS styles with JavaScript.