Add Class on Hover and Remove on MouseOut with jQuery

Last Updated on April 9, 2021 by Roshan Parihar

In this tutorial, learn how to add class on hover and remove class on mouseout. The short answer is: use the jQuery addClass() to add class and removeClass() to remove class on mouseout. You have to pass the class as the argument of these methods.

You can also use jQuery toggleClass() method to add/remove classes using the single function of jQuery. However, with this method, you can add/remove only a single class at a time in jQuery.

Let’s find out these methods with the examples given below.

How jQuery Add Class on Hover Using addClass() Function

To add class using jQuery, you have to use the addClass(). You have to pass the class name as the argument of the method. If you have certain stylings to add, the styling automatically applies on hover.

Test it Live

Output

Hover me to add class using jquery.

The above example contains the text content inside a div element. The addClass() method in jQuery add class and the styles with the class automatically apply.

jQuery Remove Class on Hover Using removeClass() Function

You can also remove the added class using jQuery. For jQuery remove class on mouseover, you have to use the removeClass() function and pass the class as the argument of it. The class argument is the class you want to remove from the div element.

Test it Live

Output

Mouseover me to remove class using jquery.

The above example contains the added CSS class. If you want to remove class, you need to mouseover over the div element given above.

Toggle Class on Mouseover Using toggleClass() Method in jQuery

In addition to the above examples, you can also use toggleClass() to toggle class of the div element on hover. It add class on hover and remove class on mouseout. This is the single function that can perform both the effects and actions with jQuery.

Test it Live

Output

Mouseover me to toggle class using jquery.

To check the toggle effects, mouseover and mouseout the above text content to see the output.

The toggleClass() function is the single method that is useful to perform the add/remove effects together. You can also use this method to add/remove other HTML elements using jQuery.

2 replies on “Add Class on Hover and Remove on MouseOut with jQuery”

  1. Tell me how to add a class with a div id. When the div is hovered using class tag

Comments are closed.