Using the .addEventListener() method, we can have a DOM element listen for a specific event and execute a block of code when the event is detected.
The DOM element that listens for an event is called the event target and the block of code that runs when the event happens is called the event handler.
let eventTarget = document.getElementById('targetElement');
eventTarget.addEventListener('click', function() {
// this block of code will run when click event happens on eventTarget element
});
- Let’s break this down!
- We selected our event target from the DOM using document.getElementById('targetElement').
- We used the .addEventListener() method on the eventTarget DOM element.
- The .addEventListener() method takes two arguments: an event name in string format and an event handler function.
- In this example, we used the 'click' event, which fires when the user clicks on eventTarget.
- The code block in the event handler function will execute when the 'click' event is detected.
- Instead of using an anonymous function as the event handler, it’s best practice to create a named event handler function. Your code will remain organized and reusable this way, even if your code gets complex. Check out the syntax:
function eventHandlerFunction() {
// this block of code will run when click event happens
}
- The named function eventHandlerFunction is passed as the second argument of the .addEventListener() method instead of defining an anonymous function within the method!
Look at the browser and notice that there are two elements, one containing informational text about JavaScript and a button. When the button is clicked, there should be more text that appears. Currently, clicking the button doesn’t seem to do anything. You are going to create an event handler to fix this!
First, create a function called showInfo() which we will use as the event handler function to make the hidden element containing the additional informational text (moreInfo) appear when the 'click' event fires.
Inside the function, create a statement that changes the .display style property of the moreInfo element to 'block'.
Now, create an event handler for a click event using .addEventListener(). Use readMore as the event target and showInfo as the event handler function.
Run your code and fire your event once you’re done.
eventTarget.addEventListener('click', function() { // this block of code will run when click event happens on eventTarget element });
function eventHandlerFunction() { // this block of code will run when click event happens }
eventTarget.addEventListener('click', eventHandlerFunction);