Monday 16 May 2011

jQuery: CSS manipulation

   


In this very short article, we will see how to manipulate CSS properties using jQuery. The main reason why, we should consider jQuery to change applied CSS styles to an object, is because we can do it on the fly, and thus basically change the appearance of an object according to some predefined event.
I assume you know a little about jQuery and how to develop functions on events. We will just see jQuery css method which has two basic usage:
1) retrieve the property of an object;
2) change the property of an object.

What's a property?
The css method has a simple syntax:
$('selector').css('css-property-name');
With the above syntax, we can determine a property for a specific div:
$("#example").html($('#example').css('background-color'));
In the above example, we are retrieving the background-color value of a div with id = "example":
<div id="example" style="width:100px;height:100px;background:blue"></div>



Change the property
We can use the CSS method to change that colour (or any other property we like). Just to follow the above example, the following snippet will change the background-color to red:
$('#example').css('background-color','red');
With the above code we change the background color, however, we can even set multiple properties for the same tag. For example we can change the background color and the font color:
$('#example').css({'background-color':'red','color':'white'});

When and where we should use it
Good question! I can think of many applications of the above method. For instance, we can use it to change the look of a piece of text on mouse hover. Or maybe change the border of an image when selected. Basically, we should use it when in need of enhancing an interface on interaction by a user. The method is simple and effective and I'm sure it can spark new ideas and usage in your web site or application.

And that's all folks! Please let me know how you used or are going to use CSS manipulation, using the comment section below!

0 thoughts:

Post a Comment

Comments are moderated. I apologize if I don't publish comments immediately.

However, I do answer to all the comments.