3.4 Introduction to Events


3.4 Introduction to Events

Often, we want our webpage to be interactive. For instance, we want our webpage to respond when the user clicks on an element, or when the user hovers over something. These are all examples of events.
As an example, the click event is triggered when the user clicks on a specific element. Consider the following code:
let div1 = document.getElementById(“div1”); div1.onclick = () => { //This executes when the user clicks on “div1” div1.style.backgroundColor = “#DDDDDD”; };
The onclick property specifies a function to be executed when the corresponding HTML element the user clicks on. Here, div1’s background color changes to “#DDDDDD” when the user clicks it.

Event Listeners

Unfortunately, we can only bind one function to the “onclick” property at a time. For example:
div1.onclick = functionA; div2.onclick = functionB;
Here, the second function will overwrite the first one. To remedy this, we can use addEventListener().
div1.addEventListener(“click”, functionA); div1.addEventListener(“click”, functionB);
This will bind both functions to div1.
In general, addEventListener() follows this syntax:
EventTarget.addEventListener(type, listener);
The type is the type of event we are “listening” for, specified by a string. In the previous example, “click”, the event of a mouse click, is the event type. Listener is the object that gets alerted of an event, usually a function.

Previous Section

3.3 Manipulating CSS
Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.