Create A Toggle Button In Javascript To Manipulate The DOM With The toggle() Method
Introduction
The toggle()
is a method of the DOMTokenList
. It removes something like a class
name from the list, and returns false
. If the class
name does not exist, it will add it to the list and return true
.
In this tutorial, You will learn to use the toggle()
method to control the visibility
of HTML elements by clicking on a button
.
Demo
You can find the demo on codepen.
Step 1 — Adding a Button And Div To The HTML
In this step, you are going to add a <button>
and a <div>
to the DOM. The Button is going to execute a function called hideMe()
upon clicking.
You will also need to add some text inside the <div>
and style it later.
<button onclick="hideMe()">Toggle Visibility</button> <div id="container">Click the "Toggle Visibility" button!</div>
Step 2 — Styling With CSS
To make the changes after toggling the button more distinct, You will need to add some styling to the <div>
element.
You also require to define a class that you want to add to the <div>
when the button is clicked.
* { box-sizing: border-box; } body { font-family: sans-serif; } #container { width: 100%; background-color: #0096c7; padding: 48px; margin: 24px 0; text-align: center; color: #fff; font-size: 2rem; } .hidden { visibility: hidden; }
Step 3 — Adding Javascript To Toggle The Visibility
In this final step, you will need to write a function to toggle the visibility
by adding the .hidden
class to the div with #container
ID.
function hideMe() { const container = document.getElementById("container"); container.classList.toggle("hidden"); }
In the code above, you have created a function called hideMe()
.
This function, grabs the <div id="container">
and add/remove the class .hidden
on toggle.
Conclusion
In this tutorial, you have learned to use the toggle()
method in Javascript and toggle the state of an element based on button clicks.
If you have followed every step in this tutorial, your code should look similar to this demo on codepen.