Pages

Thursday, June 27, 2013

How to dynamically add a CSS class for an HTML element

Here is another wonderful feature of jQuery, you can add or remove CSS class dynamically using jQuery addClass() and removeClass() methods. For example, if you want to change the background color of a DIV element for a bit of time, you can add that CSS class property on the fly.
see the example below,
HTML
<div id ="notice" class="">Please notice this area</div>
<button>Add Class</button>
jQuery
$("button").click(function(){
    $("#notice").addClass("divcls");
    setTimeout(function() { $("#notice").removeClass("divcls") }, 1000);
 });
CSS
.divcls{background-color:red;font-weight:bold;width:150px}

No comments:

Post a Comment