JS · Lesson 8

Events

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.

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.

Welcome 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).

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.

The function you give the handler doesn't run right away. The browser keeps it, and runs it each time the event happens.

A closer look

How an event handler is written

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.

Let'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.

Step 1: React to a click

Your code
const button = document.getElementById("like");button.onclick = function () {  console.log("Liked!");};
What you see

Console

    Nothing here yet. console.log() writes here.

    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.

    Step 2: Change the page on each click

    Your code
    const button = document.getElementById("like");let likes = 0;button.onclick = function () {  likes = likes + 1;  document.getElementById("likes").innerHTML = likes + " likes";};
    What you see

    Console

      Nothing here yet. console.log() writes here.

      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.

      Step 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";};
      What you see

      Console

        Nothing here yet. console.log() writes here.

        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.

        Step 4: React to typing

        Your code
        const search = document.getElementById("search");search.onkeyup = function () {  document.getElementById("echo").innerHTML = "You typed: " + search.value;};
        What you see

        Console

          Nothing here yet. console.log() writes here.

          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.

          Step 5: Use a named function

          Your code
          function sayThanks() {  document.getElementById("likes").innerHTML = "Thanks for the like!";} document.getElementById("like").onclick = sayThanks;
          What you see

          Console

            Nothing here yet. console.log() writes here.

            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.

            Step 6: The same thing, from the HTML

            Your code
            function sayThanks() {  document.getElementById("likes").innerHTML = "Thanks for the like!";}
            What you see

            Console

              Nothing here yet. console.log() writes here.

              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.

              Quick notes

              onclick When 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

              1. Count clicks.

                let clicks = 0;button.onclick = function () {  clicks = clicks + 1;};
              2. Use a named function.

                function hello() {  console.log("Hello!");}button.onclick = hello;
              onmouseover When 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

              1. Show a hint on hover.

                card.onmouseover = function () {  hint.innerHTML = "Click to read more";};
              2. Hide it again.

                card.onmouseout = function () {  hint.innerHTML = "";};
              onkeyup When 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.value What is typed in the box right now, as a string.

              Examples

              1. Count the letters typed so far.

                nameBox.onkeyup = function () {  console.log(nameBox.value.length);};
              2. Greet as you type.

                nameBox.onkeyup = function () {  hello.innerHTML = "Hi, " + nameBox.value;};

              Common mistakes

              These are mistakes many beginners make. Try clicking and typing in each mini browser to see what goes wrong.

              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();
              What you see

              Console

                Nothing here yet. console.log() writes here.

                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.

                Tip: Hand the function over without ( ): onclick = sayThanks;

                Using a capital letter in the event name

                The mistake
                const button = document.getElementById("like");button.onClick = function () {  console.log("Liked!");};
                What you see

                Console

                  Nothing here yet. console.log() writes here.

                  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.

                  Tip: Write event names in small letters: onclick, onmouseover, onkeyup.

                  Reading .value too early

                  The mistake
                  const search = document.getElementById("search");const typed = search.value;search.onkeyup = function () {  document.getElementById("echo").innerHTML = "You typed: " + typed;};
                  What you see

                  Console

                    Nothing here yet. console.log() writes here.

                    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.

                    Tip: Read .value inside the handler, so you get what's in the box when the key is let go.

                    Test 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.

                    No clicking needed. Each goal gets a check mark by itself once your code does it.

                    1. Give the #switch button an onclick. not done yet
                    2. Inside the onclick, change the text of #status. not done yet
                    3. Give the #box paragraph an onmouseover. not done yet
                    4. Give the #name box an onkeyup that reads .value and shows it in #hello. not done yet
                    Your code
                    What you see

                    Console

                      Nothing here yet. console.log() writes here.

                      Try an exercise

                      Recap

                      • An event handler is a function that runs when something happens to an element: element.onclick = function () { };.
                      • onclick reacts to clicks, onmouseover to the mouse moving onto an element, and onkeyup to a key being let go.
                      • Hand over a named function without ( ), write event names in small letters, and read an input's .value inside the handler.

                      References

                      Lesson content prepared by the WebCore F.E. team for beginner learners. The following references were used in preparing this lesson.

                      • WHATWG. HTML Standard: Event handlers (official specification). Open reference
                      • WHATWG. DOM Standard (official specification). Open reference
                      • ECMA International. ECMAScript Language Specification (official specification). Open reference