Event Listeners In JavaScript
If you’ve visited any website ever, then you’ve experienced that when click on a button, something action occurs, or maybe there is a night mode toggle that changes the colors of the website. All these things are made possible with the DOM (Document Object Model) and event listeners. The JavaScript programming language allows you to access DOM objects (ex: a button) via APIs (Application Programming Interface), such as the document.querySelector() function. You can then attach an event listener to that object and manipulate the content that is displayed on your page and add interactivity. The addEventListener() function takes in two parameters: the specified event that it is listening for (ex: mouse click or escape key) and a function that executes whenever the event is triggered.
This seems cool and all, but let’s actually try this out for ourselves to get a better idea of how this works. Here’s the idea: we want to add an event listener to a button in our web page that “listens” for a mouse click on our button. We decide that when this happens, we want to display some text underneath the button that tells us how many times we have clicked the button.
We begin by creating a simple HTML document which contains a button with a class of btn and an h2 below our button with a class of text like so:
Next, in our JavaScript, we want to add references to our button and text field by using the document.querySelector() function like so:
let btn = document.querySelector(".btn");
let text = document.querySelector(".text");
Note, that similar to CSS, the “.” before the class name tells the querySelector() function that the identifier is a class.
Next, we create a counter variable that keeps track of how many times we have clicked on the button:
let x = 0;
And our last step is to add the event listener to our button, where the first parameter is indicating that we are listening for a mouse click and the second parameter is our callback function (the function that executes when the button is clicked).
As you can see, inside our callback function we increment the counter variable and update the text content of our h2 by accessing and changing its textContent field. We are now finished and here is our final product:
We did not add any CSS to our website, so it isn’t exactly visually appealing, but it does the trick. As a bonus tip If you were curious, the DOM and JavaScript APIs also allow you to modify the CSS in real time.
Hopefully this has given you a good idea of what event listeners are and how they work. There really is quite a lot that you can do with this!
Thanks for reading!
Comments
Post a Comment