jQuery Style How to - Toggle class to apply style








Question

We would like to know how to toggle class to apply style.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'
  src='http://code.jquery.com/jquery-1.8.3.js'></script>
<style type='text/css'>
#item {<!--from ww  w. j  av  a2s .  c  o m-->
  border: 3px solid white;
}

#item.active {
  border-color: #A8402A;
}
</style>
<script type='text/javascript'>
$(window).load(function(){
    $('#item').click(function() {
        $(this).toggleClass('active');
    });
});
</script>
</head>
<body>
  <div id="item">Hello</div>
</body>
</html>

The code above is rendered as follows: