Javascript toggle class show and hide

javascript toggle class show and hide div

In this article we will go through a concept where we toggle class on click, so when user click on button we will add class open and if user click again we will remove that open class, The toggle() method of the DOMTokenList interface removes an existing token from the list and returns false. If the token doesn’t exist it’s added and the function returns true. Through Javascript toggle class show and hide we can create multiple attractive functionality and features. like toggle mobile menu, javascript dropdown menu, javascript accordians

Lets create simple javascript toggle method where we create a button and on button click we will show and hide the content

In this example, when the button is clicked, we are toggling class on mainContiner which is adding and removing open class

Understanding the toggle() Method

The toggle() method is part of the classList API and is designed to simplify the process of adding and removing classes. Its syntax is straightforward:

Other usage of toggle()

The toggle() method can also accept a second argument, which is a boolean (true of false) value. If this second argument is true, the class will be added; if false, it will be removed. This allows for more controlled behavior when toggling classes.

In this case, you can control whether the class is added or removed based on the isAdded parameter, providing flexibility in how classes are managed.

Further reading

  • React UseEffect | simplifyScript

    Understanding the useEffect hook in React

    In this article, we will learn about another React hook called useEffect(), through this article you will be able to understand what is react useEffect Hook and how to use useEffect() hook in react, this is most communally used hook after useState() hook, we mostly use this hook in every component on react now first […]
  • React useState function

    How to Use useState Hook in React Application

     In a React application, normal vanilla JavaScript may not work for some concepts. For example, if I want to toggle a class on a button click or add and remove classes, I might need to show a popup on the website. This can be easily achieved in vanilla JavaScript using the element.classList.toggle(“newClass”) method, allowing us to add […]
  • javascript DOm manipulation - simplifyscript

    What is DOM manipulation in javascript 

    In this article, we will explore JavaScript DOM manipulation, a key feature of JavaScript that allows developers to modify the Document Object Model (DOM) of a webpage. DOM manipulation enables you to dynamically alter the content and structure of HTML documents. To grasp this concept thoroughly, we’ll start by defining what the DOM is and […]