Toggle Classes On Click Using JavaScript

Toggle Classes On Click Using JavaScript

Changing the appearance of HTML elements when a user performs an action (for example, by clicking on a button) is one of the easiest ways we can add interactivity to our projects. In this tutorial, we are going to build a simple project that will change the colour of a box when the user clicks a button.

Have a look Codepen below to see what our finished project will look like:

Examining the Code

Before we get into writing our JavaScript, let's make sure we understand what's going on with the CSS. The first thing you should do is style your component to how you would like it to look in its default style, before we toggle the new class. In this case, we just apply background:red; to our .box selector.

The next step is to declare a new CSS rule for the class you want to toggle when the user clicks our button. To do this, I've create a new class called .blue and added background:blue; to it.

Make sure the class you want to toggle is declared after the default style class.

If the toggle class is declared before the default class, nothing will happen when we try to toggle the background colour from red to blue.

Adding the JavaScript

First of all, lets declare our variables.

const btn = document.querySelector(".btn");
const box = document.querySelector(".box");

The above code grabs our button and our box from the DOM so we can access it easily going forward.

The next thing we are going to do is add the "click" event listener to our button.

btn.addEventListener("click", ()=>{

})

The addEventListener() method takes two parameters. The first is the type of event type to listen for, which in this case is a click event. The second is a function that will run the code we want to execute when the event occurs.

To toggle our blue background, all we need to do is insert the following code inside our event listener:

btn.addEventListener("click", ()=>{
  box.classList.toggle('blue');
})

Now, when the button receives a click event it will run the code inside which will toggle the blue class. When it is clicked again, it will remove the blue class. Try it for yourself in your editor.

Extra Challenges

Have a look at the different event types listed by the MDN here. Scroll down to "Mouse Events" and play around with changing different properties of our red box when different user events are received. For example, try adding a new event listener that will change the border-radius of our box to 50% when the user double clicks on it (Note: you will have to create a new class that contains a border-radius of 50%).

If you found this article useful, let me know on Twitter! - @jacobcollinsdev