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.
And the html links to an external main.js file that looks like this.
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.
When setting an event listener there is the first argument of the callback that is given. This argument is the event object which contains all kinds of useful information about the event when the event triggers. This can contain things like a reference to the element that was clicked on an on click event, or the x and y position of where a canvas element was clicked and much more. In this section I will be going over some examples of event objects when working with event listeners.
In this basic example of using an event object I am setting the href property of an anchor element using the target property of the event object. the target property is a reference to the element in which the event took place. In many cases this is the element where an event listener was attached, but it can also be a child of that element because of bubbling, more on that later.
Here I have a not so basic example of using event objects and event listeners that makes use of the canvas element. Here I am drawing some circles to a canvas with the arc canvas method. The position of the circles can be changed with the mouse click and mouse move event listeners.
When using mouse events the position of the mouse click,move event and so forth can be accessed via the event objects clientX, and clientY properties. However these values are window relative and not canvas element relative so I am using the getBoundingClientRect method to adjust those values to get a canvas relative x and y position.
When the example is up and running I can change the position of the circles by moving the mouse over the canvas, as well as clicking with the canvas with the click and mouse move event listeners. I could add many more listeners and make the project far more interesting, but you get the idea.