jQuery Event How to - Hover to add/remove class








Question

We would like to know how to hover to add/remove class.

Answer


<html>
  <head>
    <script type="text/javascript" src='http://code.jquery.com/jquery-1.5.2.js'></script>
    <script type="text/javascript">
        $(document).ready(function(){<!-- w  w w . ja  v  a2 s  .  c  om-->
            $("p").hover(
                   function () { $(this).addClass("y"); },
                   function () { $(this).removeClass("y"); });
        });
    </script>
    <style>
      .y { background:yellow; }
  </style>

  </head>
  <body>
    <body>
       <p>a <div>ab</div> <div>abc</div></p>
  </body>
</html>

The code above is rendered as follows: