Toggle click event in javascript

Updated: 24-Jul-2022 / Tags: Javascript Tutorials / Views: 2899 - Author: George

Introduction

Let's see how we can toggle a click event.
Basically toggle means on and off. It means that we are switching from one state to another and back again. In this tutorial we are going to see how we can toggle a click event.

In the example below, we are gonna click once on a paragraph, and change the background color. When we click again the same paragraph, we change the background color back as it was.

Give it a try.

Let's see how we code this.

The HTML

Create a index.html file with a basic html structure, and inside the body tags place this four paragraph elements. Give every element a class of "text". We are going to use the "text" class to target the elements from the javascript file.

In line 8 we have a script tag which points to a javascript file, named script.js.
That is all the html we need, and it's very simple.

<body>

	<p class="text">This is paragraph one</p>
	<p class="text">This is paragraph two</p>
	<p class="text">This is paragraph three</p>
	<p class="text">This is paragraph four</p>

	<script src="script.js"></script>
</body>
</html>

Now let's go to the javascript file and write the toggle effect.

The javascript code

Create the script.js file, be sure both files (index.html and script.js), are in the same directory, and type the code below.

let elements = document.querySelectorAll(".text");

for(element of elements){
	element.addEventListener("click", function(){
		if(!this.dataset.clicked){
			this.setAttribute("data-clicked", "true");
			this.style.backgroundColor = "#555";
			this.style.color = "#fff";
		}else{
			this.removeAttribute("data-clicked");
			this.removeAttribute("style");
		}
	});
}

Code breakdown

  • In line 1 we use the querySelectorAll method to target all elements with a class of "text".
    let elements = document.querySelectorAll(".text");

    The querySelectorAll method will return an array containing all elements with a class of "text", and we are storing the array in the elements variable. If we do a console.log on the elements variable we see the below result.

    console.log(elements);

    We see that the elements variable is holding a NodeList containing the four p tags with the class of "text". We can use a NodeList like an array.

  • In line 3 we use a for of loop to go through all the paragraph elements inside the elements array.

    for(element of elements){
  • Inside the loop we are adding to each element an onclick event-listener. Now we can capture the click event when we click on a paragraph.

    	element.addEventListener("click", function(){
  • Every time we click on an element we are going to add a data-clicked="true" attribute. This way we have a reference to perform a check, if an element has been clicked on, or not.
    Hope it makes sense.

    So in line 5 we perform that check. We are saying that if the data-clicked attribute does not exist in the element that we just clicked on, we adding the data-clicked attribute in line 6, and we are changing the background-color in line 7.

    The keyword this refers to the clicked element.

    		if(!this.dataset.clicked){
    			this.setAttribute("data-clicked", "true");
    			this.style.backgroundColor = "#eaf0e0";
    		}
    		
  • In case that the data-clicked attribute exists on the element that we clicked on, we are going to remove it in line 9, alongside with the style tag in line 10.
    This will change back the background-color.

    		else{
    			this.removeAttribute("data-clicked");
    			this.removeAttribute("style");
    		}
    	}); // closing callback function.
    } // closing for of loop.
    		

    We could change the background-color back by saying ...

    this.style.backgroundColor = "";

    ...but what if we had like 10 css rules to change back, we had to write 10 lines of code to reset the element. So removing the style attribute...

    this.removeAttribute("style");
    ...we remove all the css rules at once.

Summary

So this is one way to toggle a click event, and it's my favorite.

Last words

Thanks for reading, i hope you find the article helpful.
Please leave a comment if you find any error's, so i can update the page with the correct code.

Source code

You can download the source code and use it in any way you like.

Times downloaded: 10

Buy me a coffee

If you like to say thanks, you can buy me a coffee.

Buy me a coffee with paypal

Comment section

You can leave a comment, it will help me a lot.

Or you can just say hi. 😉