Adding and removing a class name with Jquery

Adding and removing class names on the fly using Jquery may come in handy when if want to target specific elements on your website. Let’s say you want to give a div two different background colors. One color on hover state and another color when the mouse is out.

Well, the Jquery snippet bellow makes it a breeze. It will automatically add/remove the class name ‘hovered’ to the selected element. Then you can use this class name to apply specific styles to the hovered elemnts.

//Add and remove class names using Jquery
         function(){ $(this).addClass('hovered') },
         function(){ $(this).removeClass('hovered') }

The same results can be achieved using the Jquery function
toggleClass(). You can choose whichever you want and customize it to your preferences.

//Toggle class name on hover
$('#my-div').hover(function () {