jQuery Method How to - Invert class attribute on click with toggleClass()








Question

We would like to know how to invert class attribute on click with toggleClass().

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'
  src='http://code.jquery.com/jquery-1.7.1.js'></script>
<style type='text/css'>
.first {<!--  w ww.j a  va  2  s  .  c  o  m-->
  color: blue;
}

.second {
  color: red;
}
</style>
<script type='text/javascript'>
$(window).load(function(){
    $('#foo').click(function() {
        $(this).toggleClass('first second');
    });
});
</script>
</head>
<body>
  <button id="foo" class="first">Click Me, Watch My Color Change</button>
</body>
</html>

The code above is rendered as follows: