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 we might do that:

HTML

<div onclick="myFunction()">click me!</div>

JS

function myFunction(){
    console.log("You clicked me!");
}

Practice that a bit, and then we will learn another way.


Another Way

You can also 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.

JavaScript has short cut methods, so instead of saying addEventListener('click', function(){} you can say click(function{})

Here is an example:

<button type="button" id="my-button"></button>

<script>
function myFunction() {
   console.log("Clicked on the checkbox");
}

document.getElementById("my-button").click(myFunction());
</script>

The syntax: someHTMLElementObject.click(functionToRun)

Methods like .click(), .hover(), .keypress() are just a few. These don't take the name of the event as a string as an argument. So it is NOT: HTMLElementObject.click('click')

There are many ways to do the same thing, but it's important to be able to recognize them for what they are. Practice using different ways. This is one of the many areas of programming that will make sense after you try it a few times.