Learn From Examples Series
Suggession: Type the code manually else it won’t work.
Use javascript events like onmouseover and onmouseout to change CSS style of an object.
Code:
Code Explained:
The above code will create an inputbox and on mouseover its background colour will change to black.
this : It is used to tell the browser that the change will occure to the calling object only. In this case it is <input> tag.
style : This is used to specify that we are playing with CSS style using javascript.
backgroundColour : This is the CSS style that we are changing or Adding.
Changing more than one css style at a time.
Code:
Code Explained:
On-mouse-over, the above code will change the background colour to black and text colour to white.
Similarely on-mouse-out it will change the background colour to white and text colour to black.
Adding/removing css class dynamically
You can use setAttribute javascript method to add a class to the calling object.
Code:
.test {
background-color: #0099FF;
}
</style>
<input type="text" onmouseover="this.setAttribute(‘class’, ‘test’);this.setAttribute(‘className’, ‘test’);" onmouseout="this.setAttribute(‘class’, ”);this.setAttribute(‘className’, ”);"/>
Code Explained:
The above example sets the class of input tag to test on-mouse-over and removes the class attribute on-mouse-out.
List of Javascript Events
- onblur
- onchange
- onclick
- ondblclick
- onfocus
- onkeydown
- onkeypress
- onkeyup
- onmousedown
- onmousemove
- onmouseover
- onmouseup
- onmouseout
- onselect
In the next tutorial Modifying css style on the go using javascript. Part II, I will write about using javascript fucntions to change CSS Style dynamically.