Tuesday, March 19, 2013

jQuery / dynamic adding CSS class


How to add some css class dynamically with jQuery?
jQuery comes with addClass() function to do that.

Example of dynamically adding css class.
<html>
<head>
<title>jQuery</title>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<style type="text/css">
    .redFont{ 
        color: #FF0000;
    }
 </style>

<script type="text/javascript">
 
    $(document).ready(function()
    {
        $("#J_action_addCssClass").click( function()
        {
            $("#mymsg").addClass("redFont");
        });        
    });
 
</script>

</head>

<body> 
    
    <a id="J_action_addCssClass" href="javascript:void(0)" >Show message</a>

    <div id="mymsg">
        This is my text.
    </div>

</body>
</html>

Official documentation is here.

No comments: