30 Days Of JavaScript

Day 22: Consolidation 5

Lesson 1: Events

Making user interfaces is all about reacting to user events, and there are a lot of events you can hook into in JavaScript. We covered a few of the most important ones.

onclick

Any thing can be clicked on a web page, so we can add an onclick handler to anything we like. Let's start with a simple <button>.

1<button id="hi-button" onclick="console.log("Clicked!")">Say Hi!</button>

Or added from JavaScript like this:

1const button = document.getElementById("hi-button");
2
3button.onclick = () => {
4  console.log("hello");
5};

This passes the onclick handle an anonymous function to invoke when the button is clicked.

All events are passed an event parameter that you can access like this:

1button.onclick = (e) => {
2  console.log(e);
3};

That tells you all sorts of information about the event.

onmouseover and onmouseout

These two events let us call a function as they go over an element and then another when the mouse leaves. These will only fire on the transition and not continuously whilst we are moving the mouse around other elements.

This is where we also talked about target vs currentTarget.

To refresh your memory look at this HTML:

1<div id="container" style="background-color: red;">
2  <p id="title" style="background-color: yellow; margin: 30px;">
3    Amazing website
4  </p>
5  <p></p>
6</div>

If we add an onmouseover event handler to container like this:

1const container = document.getElementById("container");
2
3container.onmouseover = (e) => {
4  console.log(e.target);
5  console.log(e.currentTarget);
6};

Pretty ugly, I know! But ignore that for now. Hover your cursor on the red area and you will see a couple of log messages in your console showing the two properties we care about target and currentTarget. They will both say <div id"container" ....

This tells the element that triggered the event is the same one that fired the event handler.

Now hover on the yellow area.

This time the target will be <p id="title"... and the currentTarget will be <div id="container"... which tells us that the thing that first detected the event <p id="title"> is not the element that fired the event handler, which was the <div id="container">.

This tells us that events propagate up the DOM, so if you want an event to do something when, and only when, that specific element is hovered on, then you need to check that the e.target === e.currentTarget.

So I usually guard my functions with an early return like this:

1element.onmouseover = (e) => {
2  if (e.target !== e.currentTarget) {
3    return;
4  }
5  // code you want to run
6};

setTimeout

This isn't really an event in the same way that the others are but it can execute code in the future so I included it in this chapter. The time is in milliseconds remember.

1setTimeout(() => {
2  alert(`Awesome, you finished a task`);
3}, 500);

It returns a reference to the timeout that, if needs be you can call cancelTimeout() on like this:

1const myTimeout = setTimeout(() => {
2  alert(`Awesome, you finished a task`);
3}, 5000);
4
5cancelTimeout(myTimeout);

keydown

Key down lets you detect key presses. The event passed in has a .key property that so you can check which key was pressed, for example e.key === "ArrowRight"

onload

onload lets us execute some JavaScript specifically once everything on the page has finished loading. Sadly attaching it to document is flaky, so you need to attach it to window.

1window.addEventListener("load", (e) => {
2  console.log("Page loaded");
3});

Outline

Go Pro?

Upgrade to Pro for quizzes, tracked progress and a completion certificate for just $25 🚀

Want more developer tips, tricks and tools?
Then follow me:
FREE Coding Career Quick Start Guide 🚀
Discover the best way to learn to code, how to land a job and valuable resources to help your journey in this free 15 page value packed guide.
Looking to email me? You can get me on my first name at allthecode.co