Toggle Add Class Javascript

Toggle Add Class Javascript

3 min read Jun 20, 2024
Toggle Add Class Javascript

Toggle Add Class with JavaScript

This article will guide you through adding and removing a class from an element using JavaScript's classList API, making your elements dynamic and responsive.

The classList API

The classList API provides a powerful and easy way to manipulate the classes of an HTML element. It offers methods to add, remove, toggle, and check the existence of a class on an element.

Toggle Add Class with JavaScript

To toggle a class on an element using JavaScript, we will use the classList.toggle() method. This method takes the name of the class as an argument. If the class exists on the element, it will remove it. If the class doesn't exist, it will add it.

const element = document.getElementById("myElement");

function toggleClass() {
  element.classList.toggle("active");
}

// Attach the function to a button or event
document.getElementById("myButton").addEventListener("click", toggleClass);

In this example, we first select the element with the ID "myElement." Then, we create a function named toggleClass that toggles the "active" class on the element. Finally, we attach this function to a button with the ID "myButton." When the button is clicked, the toggleClass function will be executed, adding or removing the "active" class from the element.

Example: Toggle a Menu

Let's illustrate this with a simple menu that expands and collapses on click.

HTML:



JavaScript:

const menuButton = document.getElementById("menuButton");
const menu = document.getElementById("myMenu");

menuButton.addEventListener("click", () => {
  menu.classList.toggle("hidden");
});

In this example, we have a hidden menu with the class "hidden." Clicking the menu button will toggle the "hidden" class, making the menu visible or invisible.

Conclusion

The classList.toggle() method provides a straightforward way to add and remove classes from HTML elements, making your web pages more interactive and dynamic. By combining this method with JavaScript event listeners, you can create engaging user experiences.

Related Post