jQuery toggleClass() examples

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>
refresh

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>
refresh
Note that we are using position:absolute for menu-items so that it does not shifts the next element when it becomes visible. You can see more about position at Css position tutorial

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments