JavaScript

jQuery 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.

Add and Remove class on mouse hover
Add and Remove class on mouse hover

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.

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

<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>
...

JQuery addClass() and removeClass

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.

You can customize this code further as per your requirement.