buttons (likes, thumbs up etc.).
The HTML Structure
Put the following inside your HTML document’s body tags:
The parent div element (the wrapper) is only there so we can center its children elements (the box and the button) with CSS. This is cosmetic, and not necessary for this to work.
Note: if you’re using an online code editor like CodePen you can add this code in the HTML tab window. They add the rest of the HTML for you behind the scenes, including body tags.
The parent div element has a .wrapper class which has some Flexbox properties that center aligns its child elements: the box and the button. I won’t get into the how and the why of Flexbox, that’s for another
The button and the box get some basic style classes for cosmetic purposes.
The important thing to focus on here is the .bg-red class which contains the CSS background-color property with a value of '#AA2F18' (red). This is the class that we want to toggle (add or remove)
to our box element when we click on the button element.
Then we assign the two elements to their respective variables.
To select the box and button element that we want to store a reference to we’ll use the glorious querySelector method to grab our elements’ classes:
var button = document.querySelector('.button');
var box = document.querySelector('.box');
Now that we have a reference to each of our target elements, we can DOM manipulate them, by accessing their properties and methods. In this case, we want to use an event listener that listens to a click event on the button element. After the click has been detected we want to execute a function that runs the background color toggling on our box element.
To do that we’ll attach the addEventListener() method to our button element (via its variable reference). Inside this event listener method we’re adding two parameter values: 'click' (the event type),
function(). We’ll use an anonymous (unnamed) function in this example.