Event listeners in javaScript

In javaScript event listeners are methods that fire when a given event happens, such as when a mouse button is clicked, or an element looses focus. In this post I will be covering the use of addEventListener as a way to attach events to elements in client side javaScript.

1 - Event listener basics

There is more than one way to attach event listeners in client side javaScript. For the most part it is a good idea to just stick to addEventListener method as a way to attach events. However there are also some alternative ways to do so as well that involve defining a method for certain properties as well.

2 - Attaching Event listeners using addEventListener

In this section I will be covering a simple example of an event listener using the addEventListener method. This works by gaining a reference to an element by whatever means, such as with document.getElementById, and then calling the addEventListener method of that element. The first argument that I give to addEventListener is the type of event I which to attach for, and the second argument is the method that I want to fire when this event occurs.

So I have some html for this example that looks like this.

1
2
3
4
5
6
7
8
9
<html>
<head>
<title>Event Listeners</title>
</head>
<body>
<input id="button" type="button" value="click me">
<script src="main.js"></script>
</body>
</html>

And the html links to an external main.js file that looks like this.

1
2
3
4
5
6
7
var button = document.getElementById('button');
button.addEventListener('click', function(e){
console.log('foo');
});

For the most part addEventListener should be used as a way to attach events to an element. This way if I want I can attach more than one handler for the same event and element.