jQuery Event How to - Toggling class style on hover








Question

We would like to know how to toggling class style on hover.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'
  src='http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'></script>
<style type='text/css'>
.post {<!--from  w ww.j  av a 2s  .  c  om-->
  color: red;
}

.postDesc {
  color: blue;
}
</style>
<script type='text/javascript'>
$(window).load(function(){
    $(function(){
        $(".post").hover(function(){
           $(this).toggleClass("postDesc"); 
        });
    });
});
</script>
</head>
<body>
  <div class="post">Hello world!</div>
</body>
</html>

The code above is rendered as follows: