Add Remove Active Class On Click - Html Css And Javascript

5 min read Jun 22, 2024
Add Remove Active Class On Click - Html Css And Javascript

Add and Remove Active Class on Click: HTML, CSS, and JavaScript

This tutorial will guide you through adding and removing an "active" class to an element using HTML, CSS, and JavaScript, enabling you to create interactive elements on your website.

The Basics: HTML Structure

Let's start with our HTML structure. We'll create a simple list of items, where each item will be clickable:




  Active Class Example
  


  
  


This code creates a simple unordered list (<ul>) with list items (<li>).

Styling with CSS

Next, we'll style our elements using CSS. We'll create a basic style for the list items, and then add a unique style for the active item:

/* style.css */
.nav-list {
  list-style: none;
  padding: 0;
}

.nav-item {
  display: inline-block;
  margin: 0 10px;
  padding: 10px 15px;
  background-color: #eee;
  cursor: pointer;
}

.nav-item.active {
  background-color: #ddd;
  font-weight: bold;
}

In this CSS, we:

  • Remove the default list bullet points (list-style: none).
  • Make each item display inline (display: inline-block).
  • Add some basic padding and background color.
  • Set the cursor to a pointer to indicate clickability.
  • Define a specific style for the .nav-item.active class, which will be applied to the active item.

JavaScript for Interactivity

Finally, we'll use JavaScript to add and remove the "active" class when an item is clicked. Here's the JavaScript code:

// script.js
const navItems = document.querySelectorAll('.nav-item');

navItems.forEach(item => {
  item.addEventListener('click', function() {
    // Remove active class from all items
    navItems.forEach(navItem => navItem.classList.remove('active'));

    // Add active class to the clicked item
    this.classList.add('active');
  });
});

Here's how this JavaScript code works:

  1. Selecting Elements: It selects all elements with the class nav-item using querySelectorAll.
  2. Event Listener: It adds a click event listener to each of the selected items.
  3. Remove Active Class: When an item is clicked, it first loops through all items and removes the active class from them using classList.remove('active').
  4. Add Active Class: Then, it adds the active class to the clicked item using this.classList.add('active').

Putting it Together

You can combine the HTML, CSS, and JavaScript code in separate files or within the same file. When you run this code, clicking on any list item will:

  • Remove the "active" class from any previously active item.
  • Apply the "active" class to the clicked item, highlighting it with the styling defined in your CSS.

This simple example demonstrates the fundamental approach to adding and removing active classes in HTML, CSS, and JavaScript. You can extend this technique to create more complex interactions, such as navigation menus, tabs, and other dynamic UI elements.