How To Add and Remove an Active Class With jQuery

How To Add and Remove an Active Class With jQuery

This article demonstrates how to add or remove a CSS active class using jQuery by changing a class name on an HTML list item when clicked.

This article was first seen on and republished from csstutorial.io

Add and Remove an Active Class With jQuery
Add and Remove an Active Class With jQuery

HTML

Down below we use HTML to construct an unordered list menu. The menu consists of four list elements. Additionally, the first menu includes a class called active. This class name is the basis of this demonstration.

<div class="menu-container">
  <ul class="menu">
    <li class="active">Home</li>
    <li>About</li>
    <li>Contact</li>
    <li>Photo</li>
  </ul>
</div>

CSS

The CSS styles below give the menu visibility and structure for this demonstration. We use a CSS gradient on the HTML and Body elements while using CSS flexbox to center the menu vertically and horizontally. As you see below we define some styles for the “.active” class. The active class when tagged to an HTML element sets the CSS text color to black and the CSS background to #9bd0eb.

.menu {
  list-style: none;
}

.menu li {
  font-size: 20px;
  margin: 10px;
  padding: 10px;
  cursor: pointer;
  display: inline-block;
  border-radius: 4px;
}

.menu {
  width: 450px;
  margin: 0 auto;
  background: rgba(16 18 27 / 40%);
  border-radius: 8px;
  backdrop-filter: blur(20px);
}

.menu-container {
  margin: 0;
  padding: 0;
  height: 100%;
  -webkit-box-align: center !important;
  -ms-flex-align: center !important;
  align-items: center !important;
  -webkit-box-pack: center !important;
  -ms-flex-pack: center !important;
  justify-content: center !important;
  display: -webkit-box !important;
  display: -ms-flexbox !important;
  display: flex !important;
}

.active {
  background: #9bd0eb;
  color: black;
}

jQuery

We use jQuery in the example. jQuery is a library framework of JavaScript that provides easy-to-use methods. In addition, jQuery makes it easy to bind to elements by selector reference. By binding to the elements it turns the functions into listeners. Below we attach an on-click listener to the unordered list. Whenever we click on a list item nested within the unordered list we trigger the function. The function removes all active classes on the elements and applies it to the current element we clicked.

$('.menu').on('click', 'li', function() {
    $('.menu li.active').removeClass('active');
    $(this).addClass('active');
});

Edit this demonstration on codepen.io

Installing jQuery

jQuery can easily be installed by including the script below in the header of each page.

<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>

Recommended Articles

Comments

Tip: Thoughtful and well written comments are voted up more often.
0 Comments

No Comments.