7. DOM Events and Interactivity
We want our website to be interactive; essentially, we would like our website to respond to inputs from the user. These inputs - clicking buttons, submitting forms, pressing keys, and even scrolling up or down - are turned into events by the browser, which our code can then respond to.
7.1 Listening to Events
In order to respond to events, we first listen to an element (an event target) for specific events and pass in a function that specifies our response to that event.
As an example, let's consider the task of making a button that creates a pop-up window when the user clicks on it. Starting with the following page:
<div id="button">
Click me!
</div>
Let's add a listener to the button to listen for a click
event. We use the Element.addEventListener
function.
var btn = document.getElementById("button");
btn.addEventListener("click", function(e) { alert("Hello!"); });
Now when the user clicks the button, they will get a pop-up that says "Hello!". In further detail, when the user clicks the button, a click
event is fired with the btn
element as an event target; since we added a function as an event listener, this function gets called with the event object itself as an argument.
7.1.1 Event Bubbling
By default, events will bubble up (propagate up) the DOM tree when they are fired on a given node in the tree. For example, in the following page, if the user clicks on the innermost div, the click
event will actually fire for all nodes in the tree!
<div id="grandparent">
<div id="parent">
<div id="button">
Click me!
</div>
</div>
</div>
Sometimes this is useful (for example, if we want a container to do something based on whether an inner element was clicked). Other times, it's not so useful and can even be annoying. For example, suppose we are designing a game:
HTML:
<div id="danger">
<div id="goal">
GOAL ZONE CLICK ME
</div>
DANGER ZONE DON'T CLICK ME
</div>
JavaScript:
document.getElementById("goal").addEventListener("click", function(e) { alert("you win!"); });
document.getElementById("danger").addEventListener("click", function(e) { alert("you lose!"); });
Say the user loses if they click in the danger zone and they win if they click in the goal zone. However, a click
event in the goal zone element will result in the a click
event also firing for the danger zone element. We can prevent this by calling Event.stopPropagation
on the click event in our event listener:
document.getElementById("goal").addEventListener("click", function(e) {
alert("you win!");
e.stopPropagation();
});
document.getElementById("danger").addEventListener("click", function(e) { alert("you lose!"); });
7.1.2 Input Events
Events are most useful when combined with input elements. Let's look at the example of a textbox that responds when the user types something and presses enter:
HTML:
<input type="text" id="namebox" />
<div id="response"></div>
JavaScript:
document.getElementById("namebox").addEventListener("change", function(e) {
var responseBox = document.getElementById("response");
responseBox.innerHTML = "You just typed " + e.target.value;
});
The relevant code is the last line; we can access the event target (which in this case is the textbox HTML element) with e.target
and access the input element's value with e.target.value
.
7.1.3 Event Defaults
Some events have some special default behavior. For example, a click
event fired on an anchor tag causes the browser to navigate to whatever URL the anchor tag points to. We can override this behavior in our event listeners by calling e.preventDefault
, which also has the added behavior of canceling the entire event.
7.1.4 Removing Event Listeners
Just as we can add event listeners, we can also remove event listeners using Element.removeEventListener
. This event accepts an event type and a reference to the listener function to be removed and removes the event listener if found. Example:
var handleBodyClick = function(e) {
console.log("document body was clicked!");
}
document.body.addEventListener("click", handleBodyClick);
// we decided it was too annoying so now let's remove it.
// remember that we need to keep a reference to the function to remove!
document.body.removeEventListener("click", handleBodyClick);
7.2 Types of Events
This is just a small selection of the most common events. See the official documentation for more.
7.2.1 Mouse Events
click
- The user has tapped or clicked on the element.mouseover
- The user is hovering over the element or one of its children with the mouse pointer.mousedown
- The user has begun pressing down on their mouse while on the element. This is useful for click-and-hold or long-press events.mouseup
- The user has released their mouse over the element.
7.2.2 Keyboard Events
keydown
- ANY key is pressed. TheEvent
object passed into the callback function will contain the key code.keyup
- ANY key is released.
7.2.3 Focus Events
focus
- The element has received focus from the user. Typically, this means that they have either clicked on it, or, in the case of a text input, have begun typing in it. (does not bubble)blur
- The element has lost focus. (does not bubble)