RSS
 

Archive for the ‘CSS’ Category

Learn From Examples: Modifying css style on the go using javascript, Part I

26 Jul

Learn From Examples Series

Suggession: Type the code manually else it won’t work. :P

Use javascript events like onmouseover and onmouseout to change CSS style of an object.

Code:

<input onmouseover="this.style.backgroundColour=’#000000′;" onmouseout="this.style.backgroundColour=’#ffffff’;" type="text" />
 

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:

<input type="text" onmouseover="this.style.backgroundColour=’#000000′;this.style.color=’#ffffff’" onmouseout="this.style.backgroundColour=’#ffffff’;this.style.color=’#000000′;">
 

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:

<style type="text/css">
.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

  1. onblur
  2. onchange
  3. onclick
  4. ondblclick
  5. onfocus
  6. onkeydown
  7. onkeypress
  8. onkeyup
  9. onmousedown
  10. onmousemove
  11. onmouseover
  12. onmouseup
  13. onmouseout
  14. 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.