Events and Event Delegation in Vanilla JavaScript

Elizabeth
2 min readDec 15, 2020

There are many kinds of events in Vanilla JavaScript, today we are going to talk about a click event. Remember when reading the following code ‘click’ can be replaced by any event action. Examples include hover, mouseover, DOMContentLoaded, and many more. However let’s start with the basics. In this example we are adding an event lister to the document but you can add an event lister to any object on the DOM or Document Object Model (DOM).

Event listener syntax for vanilla JavaScript.

As you can see above the event listener takes two arguments. The first is the event, as stated above we are using ‘click,’ and the second is a function. The format for this can be written a number of ways. Probably the most efficient is using a callback function. A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action. That callback function takes in the event as an argument. This may sound confusing, but it is really just a way to keep track of what was clicked.

Here we are manipulating numbers on the dom. A different function has set the number to increment by one every second. The buttons below that number are linked to events that add, subtract, like a number, and even pause the count. This all happens in that one event listener we wrote above. More accurately that is where the event is called. The call back function does all the heavy lifting.

Instead of writing out event our callback function is using the argument e.

Using the IDs the same way we identify objects in CSS, we are able to figure out which button was clicked by with ‘e.target.id.’ E.target signifies the event’s target, and ID just tells us the ID of the target. Our if statement delegates which lines of code to follow. In a nutshell, thats event delegation! It can get as complicated as you need it to be. Check out the full code here.

--

--