03-Event Listeners
Last updated
Last updated
It's important for you to know that the DOM is listening
for all kinds of . In this module, we'll send some event listener methods so that the DOM can listen for activity.
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:
So here's how this works: 1. First of all, remember that the searchForm
variable targets the form element in the html
page:
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 the submit
event fires on a . When this event happens (the form is submitted by pressing the submit button), we will fire off a function called fetchResults
, 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 called nextPage
. When we click on the previous button, we run previousPage
.
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.