- Demonstrate triggering event listeners on DOM nodes with
addEventListener()
We know how to manipulate nodes in the DOM by using JavaScript. We also know that events can be handled and can do work inside callback functions when the event is triggered. JavaScript programmers often say we are "listening" for an event in order to "execute" or "call" a callback function.
In order to teach nodes (or, "elements") to "listen" for an event, we use addEventListener()
.
It allows us to associate "hearing" an event with executing a callback.
addEventListener()
takes two arguments:
- the name of the event
- a callback function to "handle" the event
Take a look at index.html
in the browser. When you click in the <input>
area, nothing happens. Now let's set up some event handling.
Start by adding an event listener for the click
event on the input#input
element in index.html
.
Try out the following in the Chrome DevTools console:
const input = document.getElementById('input');
input.addEventListener('click', function(event) {
alert('I was clicked!');
});
When you click inside of input#input
, now, you will get an alert box.
Take this code and paste it into the index.js
file's addingEventListener
function.
Let's review the parts of this code:
- The node that will be doing the listening. We store that node in the
main
constant - The invocation of
addEventListener
on the node that will be doing the listening - The first argument is the event name to listen for
- The second argument is the callback function. It's work that will be executed when the node "hears" the event
When you have pasted the solution into the addingEventListener
function, your
tests should pass when you run learn
. This means you can run learn submit
and move to the next lesson!
View Interacting with the DOM via JavaScript Event Listeners on Learn.co and start learning to code for free.