jQuery toggleClass can be used to toggle a class (add or remove depending upon current state) in an element (or set of matched elements). In case one want to toggle multiple classes, the classes can be separated by space.
Here are some examples.
jQuery toggleClass on click
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script> <style type="text/css"> .red {color: red;} .greenbg {background-color: green;} </style> <h2 class="red">Click to change background color</h2> <script> $("h2").click(function() { $(this).toggleClass("greenbg"); }); </script>
Use toggleClass to implement a basic menu
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script> <style type="text/css"> #menu-items { position:absolute; background-color:lightgray; margin: 0px; display:none; } #menu-items.active {display:block;} </style> <div id="menu">Click to show/hide menu items</div> <ul id="menu-items"><li>item1</li><li>item2</li><li>item3</li></ul> <p>This is some random text for the purpose of tutorial.</p2> <script> $( "#menu" ).click(function() { $("#menu-items").toggleClass("active"); }); </script>