JavaScript and the Web — Handling Events
By: John Au-Yeung
Tags: Programming, JavaScript, Software Development, Web Development, Technology

Photo by Waranya Mooldee on Unsplash

JavaScript is one of the most popular programming languages in the world. To use it effectively, we’ve to know about the basics of it.

In this article, we’ll look at how we can handle events in JavaScript.

Event Handlers

We can add event handlers to listen to user events.

Events include things like inputs and mouse clicks.

For instance, we can write:

window.addEventListener("click", () => {

console.log("clicked");

});

Then we listen to clicks on the browser tab and log 'clicked' if something is clicked.

addEventListener is used to listen to events of our choice.

Events and DOM Nodes

We can also call addEventListener to listen to events triggered by a DOM node.

For instance, given the following HTML:

<button>Click me</button>

We can write:

const button = document.querySelector("button");

button.addEventListener("click", () => {

console.log("clicked.");

});

to listen to click events of a button.

Then when we click the Click me button, we see 'clicked' logged.

There’s also a removeEventListener method which takes an event listener as an argument to remove it.

For instance, we can write:

const button = document.querySelector("button");

const clickOnce = () => {

console.log("Done.");

button.removeEventListener("click", clickOnce);

}

button.addEventListener("click", clickOnce);

Then the clickOnce listener will only run once and then it won’t run again since we called removeListener with it as the argument.

Event Objects

Event objects are pass into event listeners and we can use it to get more information about an event.

For instance, we can write:

const button = document.querySelector("button");

button.addEventListener("mousedown", event => {

if (event.button === 0) {

console.log("left");

} else if (event.button === 1) {

console.log("middle");

} else if (event.button === 2) {

console.log("right");

}

});

Now we listen to the mousedown event of the button.

It’s triggered when we click the button.

If the button property is 0, then the left button is clicked.

If it’s 1, then the middle button is clicked.

If it’s 2, then the right button is clicked.

So when we left-click, we get 'left' logged and when we right-click, we get 'right' logged.

The type property would have the string which identifies the event, such as 'click' or 'mousedown' .

Propagation

In JavaScript, events propagate outward from then originating element all the way to the browser window.

The event handlers for the parent, grandparent, and so on will all run if they exist by default.

To stop this, we can call the stopPropagation method on the event object.

For instance, we can write:

const button = document.querySelector("button");

button.addEventListener("mousedown", event => {

event.stopPropagation();

if (event.button == 0) {

console.log("left");

} else if (event.button == 1) {

console.log("middle");

} else if (event.button == 2) {

console.log("right");

}

});

Now it’s won’t propagate to the parent, grandparent, and so on.

We can also use the target property to add a listener than can listen to actions from multiple elements.

For instance, given the following HTML:

<button>foo</button>

<button>bar</button>

<button>baz</button>

We can write:

window.addEventListener("mousedown", event => {

if (event.target.nodeName == "BUTTON") {

console.log(event.target.textContent)

}

});

Then we get 'foo' , 'bar' , 'baz' logged depending on which button we which since the textContent has the content of the button.

Default Actions

Default actions are associated with many events.

To prevent the default action, we can call preventDefault() to stop it from happening.

Event handlers are called before the behavior takes place, so we can to it there.

For example, if we have the following HTML:

<a href='http://example.com'>example</a>

Then we can stop people from clicking the link to go to the page by writing:

const link = document.querySelector("a");

link.addEventListener("click", event => {

console.log("stopped");

event.preventDefault();

});

event.preventDefault(); stop the default action, which is to go to the page with the URL.

Key Events

The keydown event is trigger when we press a key, keyup event when a key is released.

For instance, if we have the following HTML:

<p>

foo

</p>

We can write:

window.addEventListener("keydown", event => {

if (event.key === "g") {

document.body.style.background = "green";

}

});

window.addEventListener("keyup", event => {

if (event.key === "g") {

document.body.style.background = "";

}

});

Then when we press the G key, the background will turn green.

It’ll turn back to white when we release it.

The key property has the key that’s pressed.

Photo by Gustavo Zambelli on Unsplash

Conclusion

We can detect mouse and keyboard events with the event object.

Also, we can add and remove listeners from a DOM object by passing in an event listener.