Making the page react to clicks, hovers and typing
Until now, your code ran once, as soon as the page opened. Events let your code wait, and run when the visitor does something: click a button, point at a box, or type a word.
flag
What you'll learn
What an event is, and how to run code when one happens.
How to react to clicks with onclick and to the mouse with onmouseover.
How to react to typing with onkeyup, and read what was typed with .value.
waving_handWelcome to events
An event is something that happens on the page, like a click, a key press or the mouse moving over an element.
You can give an element an event handler: a function that runs every time that event happens to it.
Event handlers bring the last lessons together: you find an element (Lesson 1), write a function (Lesson 5), and inside it you change the page or check a value with if (Lesson 3).
doorbell
Think of a doorbell. It doesn't ring all day. It waits, and rings only when someone presses it.
A motion-sensor light waits for someone to walk by, and a keyboard key does its job when your finger lets go.
An event handler waits in the same way for onclick, onmouseover or onkeyup.
doorbellA doorbellRings when someone presses it.button.onclick = function () { };
lightbulbA motion-sensor lightTurns on when someone walks by.box.onmouseover = function () { };
keyboardA keyboard keyDoes its job when your finger lets go.input.onkeyup = function () { };
Now let's see the code ↓
doorbellA doorbellRings when someone presses it.button.onclick = function () { };
lightbulbA motion-sensor lightTurns on when someone walks by.box.onmouseover = function () { };
keyboardA keyboard keyDoes its job when your finger lets go.input.onkeyup = function () { };
The function you give the handler doesn't run right away. The browser keeps it, and runs it each time the event happens.
searchA closer look
How an event handler is written
buttonthe element
.go inside
onclickthe event
=put in
function () { ... }what to do (runs later)
function () { } without a name is called an anonymous function. It doesn't need a name because the handler keeps it. You can also give a named function, like button.onclick = sayThanks;.
The events in this lesson
onclick runs when the element is clicked, or tapped on a phone. onmouseover runs when the mouse pointer moves onto the element, and onmouseout when it leaves.
onkeyup runs when a key is let go, so the letter you typed is already in the box.
The event names are all small letters.
Reading what was typed: .value
An <input> box keeps what's typed in it in its value property, as a string. Read it inside the handler, so you get what's in the box at that moment.
Handlers in the HTML
You can also write a handler as an HTML attribute: <button onclick="sayThanks()">. It works the same way, and you'll see it in many examples online.
Keeping handlers in the JS tab keeps the HTML clean and all your JavaScript in one place.
One more way: addEventListener
button.addEventListener("click", sayThanks); does the same job as button.onclick = sayThanks;. The event name has no "on" in front of it.
One difference: an element can have only one onclick, but it can have many listeners.
constructionLet's build it
Let's make Front Page Bytes react to its readers. The HTML and CSS stay the same in every step: a Like button, a hover box, a search box and a line under it.
These steps wait for you, so click, point and type inside the mini browser to see them work.
1Step 1: React to a click
Your code
const button = document.getElementById("like");button.onclick = function () { console.log("Liked!");};
Nothing happens when the page opens. The function is only kept for later. Click Like in the mini browser, and the console shows Liked!, once for every click.
likes is declared outside the function, so it keeps its value between clicks. Each click adds 1 and shows the new count. Click a few times and watch it go up.
3Step 3: React to the mouse
Your code
const tip = document.getElementById("tip");tip.onmouseover = function () { tip.innerHTML = "Thanks for stopping by!";};tip.onmouseout = function () { tip.innerHTML = "Hover over me";};
Point at the white box. onmouseover changes its text, and onmouseout puts the old text back when the pointer leaves. On a phone, tapping the box may do the same.
Click the search box and type a few letters. Each time a key is let go, onkeyup reads search.value, what's in the box right now, and copies it into the line below.
5Step 5: Use a named function
Your code
function sayThanks() { document.getElementById("likes").innerHTML = "Thanks for the like!";}document.getElementById("like").onclick = sayThanks;
sayThanks is declared first, then given to the button. There are no ( ) after sayThanks on line 5, because you're handing the function over, not running it. Click Like to see it work.
6Step 6: The same thing, from the HTML
Your code
function sayThanks() { document.getElementById("likes").innerHTML = "Thanks for the like!";}
Open the HTML tab: the button now has onclick="sayThanks()". Here the ( ) are needed, because the attribute holds code to run. The JS tab only declares the function. Click Like, and the result is the same as in step 5.
sticky_note_2Quick notes
onclickWhen it's clicked
button.onclick = function () { };
How to use
element.onclick = function () { };Runs the function each time the element is clicked.
element.onclick = name;Uses a function you already declared. No ( ) after the name.
onclick="name()"The same thing, written as an attribute in the HTML.
Examples
Count clicks.
let clicks = 0;button.onclick = function () { clicks = clicks + 1;};
Use a named function.
function hello() { console.log("Hello!");}button.onclick = hello;
onmouseoverWhen the mouse moves onto it
box.onmouseover = function () { };
How to use
element.onmouseover = function () { };Runs when the mouse pointer moves onto the element.
element.onmouseout = function () { };Runs when the pointer moves off it again.
Phones and tablets have no mouse, so hover may not work there.
Examples
Show a hint on hover.
card.onmouseover = function () { hint.innerHTML = "Click to read more";};
Hide it again.
card.onmouseout = function () { hint.innerHTML = "";};
onkeyupWhen a key is let go
input.onkeyup = function () { };
How to use
input.onkeyup = function () { };Runs each time a key is let go inside the input.
input.valueWhat is typed in the box right now, as a string.
Examples
Count the letters typed so far.
nameBox.onkeyup = function () { console.log(nameBox.value.length);};
These are mistakes many beginners make. Try clicking and typing in each mini browser to see what goes wrong.
error
Adding ( ) when handing over a function
The mistake
function sayThanks() { console.log("sayThanks ran"); document.getElementById("likes").innerHTML = "Thanks for the like!";}document.getElementById("like").onclick = sayThanks();
sayThanks() runs the function right away, as the page opens, before anyone clicks. The page already says Thanks for the like!, and the console shows it ran.
The handler gets the function's result, undefined, so clicking does nothing.
tips_and_updatesTip: Hand the function over without ( ): onclick = sayThanks;
error
Using a capital letter in the event name
The mistake
const button = document.getElementById("like");button.onClick = function () { console.log("Liked!");};
onClick with a capital C isn't an event. JavaScript just makes a new property with that name, and there's no error. Click Like: nothing shows in the console.
tips_and_updatesTip: Write event names in small letters: onclick, onmouseover, onkeyup.
Line 2 reads the box once, when the page opens and the box is still empty. Type in the search box: the line below always says You typed: with nothing after it.
tips_and_updatesTip: Read .value inside the handler, so you get what's in the box when the key is let go.
quizTest your knowledge
Write JavaScript in the JS tab. The button is ready in the variable lightSwitch. When your goals are done, click, point and type in the mini browser to try your page.
auto_awesomeNo clicking needed. Each goal gets a check mark by itself once your code does it.
Give the #switch button an onclick.not done yet
Inside the onclick, change the text of #status.not done yet
Give the #box paragraph an onmouseover.not done yet
Give the #name box an onkeyup that reads .value and shows it in #hello.not done yet