03-Event Listeners
It's important for you to know that the DOM is listening
for all kinds of events. In this module, we'll send some event listener methods so that the DOM can listen for activity.
target.addEventListener()
We'll use the addEventListener()
method here. This method will help us identify a target and then add an event listener on that target. Event targets can be an element, the document object, the window object, or any other object that supports events.
Let's discuss where events are going to happen in our app: 1. We want to submit a form that contains a query: "Sports", "Politics", "Weather", etc. 2. We want to be able to toggle through the results when we click on the next or previous button.
Let's look at the syntax of using this method:
//1 //2
searchForm.addEventListener('submit', fetchResults);
nextBtn.addEventListener('click', nextPage); //3
previousBtn.addEventListener('click', previousPage); //3
So here's how this works: 1. First of all, remember that the searchForm
variable targets the form element in the html
page:
const searchForm = document.querySelector('form');
We use the searchForm
variable and call the addEventListener
method on it. We want to listen for things happening on the particular element, which in this case is the searchForm
.
The event that we're looking for is the
submit
event. This is an HTML form event. Note that thesubmit
event fires on a form, not a button. When this event happens (the form is submitted by pressing the submit button), we will fire off a function calledfetchResults
, the second parameter in the function.The same is true for the other two items, except that they called are
click
events. When we click on the next button, we fire off a function callednextPage
. When we click on the previous button, we runpreviousPage
.
Note that the click
event is fired when a pointing device button (usually a mouse's primary button) is pressed and released on a single element.
Last updated