Event Listeners
Your Browser (Chrome, IE, Safari, Firefox) has a loop going that is always checking for certain events. These events include mouse clicks (right, left, double), key presses, and even the mouse moving, as well as many others.
Here is a list of events. It's overwhelmingly long, so let's focus on just the click event for now.
Often JavaScript functions are created that are run when certain events happen such as a click of the mouse on a certain area or thing.
You will need to attach that event (let's say a mouse click on a button or a mouse over) to an HTML element, or even the entire body of the document.
Here's how you may have seen that done:
HTML
<div onclick="myFunction()">click me!</div>
JS
function myFunction(){
console.log("You clicked me!");
}
Be aware that on
methods belong to your element as a property, but we will learn another way to add event listeners
.
Add an event listener
Select the HTML Element within your JavaScript and set up the event listener there with the addEventListener()
method.
If selecting DOM elements (which are also HTML Elements) is new to you, read this. Here is an example:
HTML
<div id="this-div">click me!</div>
JS
document.getElementById("this-div").addEventListener('click', function(){
console.log("You clicked me!");
})
Look back at the JavaScript. How many arguments does addEventListener()
take?
If you said two, you are correct. What are each of those arguments?
If you said, "The first one is a string, and the second one is an anonymous function," you are correct!
The addEventListener()
method is looking for one of many strings... "click"
, "mouseover"
, "keypress"
and "hover"
are a few. Here is a list of all the events you could use instead of click
but without the 'addEventListener' part.