• Seo Expert
  • Khaali Paper

Add/Remove Class on Mouseover/Mouseout

To add the class on hover, jQuery addClass() will add a class from a specified elements and remove the class on mouseout, use the jQuery removeClass() method.

Using jQuery addClass() and removeClass, pass the class as the argument of the function. Add one or more classes to an selected HTML elements use the addClass() method. The class is to be added to the class attribute of each matched element. Hover on one element and add a class to another selected div element and mouseout removed the class from selected div elements.

Add and Remove class on mouse hover

Example: In this tutorial we can learn how to add class and remove class on mouseover and on mouseout.

1
2
3
4
<script>
  $(document).ready(function () {
    $(".box").hover(
      function () {
        $(this).addClass("box-hover");
      },
      function () {
        $(this).removeClass("box-hover");
      }
    );
  });
</script>
You can use toggleClass on hover event
<script>
  $(document).ready(function () {
    $(".box").hover(function () {
      $(this).toggleClass("box-hover");
    });
  });
</script>
HTML
<div class="box">1</div>
<div class="box">2</div>
<div class="box">3</div>
...
//After mouseover
<div class="box box-hover">1</div>
<div class="box">2</div>
<div class="box">3</div>
...

The jQuery addClass() and removeClass will be work in any browser on any element.

Description: In this example we are adding the .box-hover class to .box class with the new css property like (change background color, font color and height of div) on mouseover and also remove the class .box-hover from the .box after the mouseout.

Related Questions

- JQuery hover over one element & add a class to another HTML elements.

- How to remove class and add another class to a div, when i hover the other div.

- How to add css class on mouse hover using jQuery.

- On mouse over I want to add a class to selected div and on mouseout remove the that class.

JQuery addClass() and removeClass