IntermediateLesson 13 of 306 min read

Events: click, input, keyboard and the event object

Make pages respond to clicks, typing and keys using addEventListener, the event object and preventDefault.

In this lesson you will

  • Attach listeners with addEventListener
  • Use the event object
  • Stop default behaviour with preventDefault
  • Respond to typing and keys

About 18 minutes

Making the page listen

A waiter does nothing until a customer raises a hand. A page is the same. It sits quietly until the visitor does something: clicks, types, scrolls, presses a key, touches the screen. Each of those happenings is called an event, and JavaScript lets you say: “when this happens to that element, run this function.”

addEventListener

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

button.addEventListener("click", function () {
  console.log("Saved!");
});

// the same, with an arrow function
button.addEventListener("click", () => console.log("Saved!"));

The first argument is the event name as a string. The second is the function to run, called a handler or callback. Notice that you pass the function itself, without brackets after it. If you wrote handler(), it would run immediately instead of waiting for the event.

Make the button count clicks. Show the total in the paragraph each time.

<button id="btn">Click me</button>
<p id="out">Clicks: 0</p>
<script>
  let count = 0;
  const btn = document.getElementById('btn');
  const out = document.getElementById('out');
  // add a click listener that increases count and updates out
</script>

Inside the handler: count++; out.textContent = ‘Clicks: ‘ + count;

<button id="btn">Click me</button>
<p id="out">Clicks: 0</p>
<script>
  let count = 0;
  const btn = document.getElementById('btn');
  const out = document.getElementById('out');
  btn.addEventListener('click', function () {
    count++;
    out.textContent = 'Clicks: ' + count;
  });
</script>

Common events

Event Fires when
click An element is clicked or tapped
dblclick Double click
mouseover / mouseout The pointer enters or leaves
input The value of a field changes, on every keystroke
change A field loses focus after changing, or a select/checkbox changes
submit A form is submitted
keydown / keyup A key is pressed or released
focus / blur A field gains or loses focus
scroll The page or element scrolls
load / DOMContentLoaded The page has loaded

The event object

Every handler automatically receives an event object describing what happened. By convention it is named e or event.

document.addEventListener("click", (e) => {
  console.log(e.type);        // "click"
  console.log(e.target);      // the element that was clicked
  console.log(e.clientX, e.clientY);   // pointer position
});

input.addEventListener("keydown", (e) => {
  console.log(e.key);         // "a", "Enter", "Escape"...
  if (e.key === "Enter") console.log("Submitted");
});

Show the key the user presses. Click inside the result, then press keys. Add a line so pressing Escape clears the display.

<style>body{font-family:Arial;padding:16px} #k{font-size:40px;font-weight:800;color:#5A28C8;min-height:56px}</style>
<p>Click here, then press any key:</p>
<div id="k">?</div>
<script>
  const k = document.getElementById('k');
  document.addEventListener('keydown', function (e) {
    k.textContent = e.key;
    // if the key is Escape, show ? again
  });
</script>

if (e.key === ‘Escape’) { k.textContent = ‘?’; }

<style>body{font-family:Arial;padding:16px} #k{font-size:40px;font-weight:800;color:#5A28C8;min-height:56px}</style>
<p>Click here, then press any key:</p>
<div id="k">?</div>
<script>
  const k = document.getElementById('k');
  document.addEventListener('keydown', function (e) {
    k.textContent = e.key;
    if (e.key === 'Escape') { k.textContent = '?'; }
  });
</script>

preventDefault: stopping the browser’s default

Some elements have built-in behaviour: links navigate, forms reload the page. Often you want your own code to take over. e.preventDefault() cancels the default.

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

form.addEventListener("submit", (e) => {
  e.preventDefault();      // do not reload the page
  console.log("Handled by JavaScript");
});

document.querySelector("a.fake").addEventListener("click", (e) => {
  e.preventDefault();      // do not follow the link
});

Listening to input as the user types

Show a live character count under the text box. It should update as you type, and turn a warning colour above 20 characters.

<style>body{font-family:Arial;padding:16px} input{padding:10px;font-size:16px;width:90%} #c{margin-top:8px;color:#5F5B80}</style>
<input id="t" placeholder="Type here...">
<div id="c">0 / 20</div>
<script>
  const t = document.getElementById('t');
  const c = document.getElementById('c');
  t.addEventListener('input', function () {
    // update c.textContent and colour
  });
</script>

const n = t.value.length; c.textContent = n + ‘ / 20’; c.style.color = n > 20 ? ‘#D63384’ : ‘#5F5B80’;

<style>body{font-family:Arial;padding:16px} input{padding:10px;font-size:16px;width:90%} #c{margin-top:8px;color:#5F5B80}</style>
<input id="t" placeholder="Type here...">
<div id="c">0 / 20</div>
<script>
  const t = document.getElementById('t');
  const c = document.getElementById('c');
  t.addEventListener('input', function () {
    const n = t.value.length;
    c.textContent = n + ' / 20';
    c.style.color = n > 20 ? '#D63384' : '#5F5B80';
  });
</script>

Removing a listener, and one-time listeners

function sayHi() { console.log("Hi"); }

btn.addEventListener("click", sayHi);
btn.removeEventListener("click", sayHi);   // needs the same function

btn.addEventListener("click", () => console.log("Once only"), { once: true });

Several listeners and old-style handlers

An element can have many listeners for the same event; they all run in the order added. You may see older code like button.onclick = function(){...} or onclick="..." inside the HTML. These work but allow only one handler and mix behaviour into markup, so prefer addEventListener.

Common mistake

Writing btn.addEventListener("click", doIt()) with brackets. That calls doIt straight away and passes its result. Pass doIt without brackets, or wrap it: () => doIt(5).

Touch and mouse together

The click event also fires for taps on phones, so you rarely need separate touch code. For drag and swipe, look at pointer events such as pointerdown and pointermove later.

Worked example: a hover and click counter

Events combine nicely. This small example reacts to the pointer entering a card, leaving it, and clicking it, three events on one element, each doing one tiny thing.

const card = document.querySelector(".card");
let clicks = 0;

card.addEventListener("mouseenter", () => card.classList.add("lift"));
card.addEventListener("mouseleave", () => card.classList.remove("lift"));
card.addEventListener("click", () => {
  clicks++;
  card.querySelector("span").textContent = clicks;
});

Keeping handlers small and focused makes them easier to read and to fix. If a handler grows beyond ten lines, move the work into a named function and call it from the handler.

Check what you learned

Five quick questions. Pick an answer and you will see straight away whether it is right and why.

Which is the correct way to attach a click handler?

  1. Pass handler() with brackets
  2. Pass handler without brackets
  3. Assign to btn.click
  4. Call btn.listen

Pass the function without calling it.

What does e.preventDefault() do?

  1. Deletes the element
  2. Stops all JavaScript
  3. Reloads the page
  4. Stops the browser’s default action

It cancels default behaviour such as form submission.

Which event fires on every keystroke in a text field?

  1. change
  2. input
  3. blur
  4. load

input fires immediately as the value changes.

What is e.target?

  1. The page URL
  2. The key pressed
  3. A number
  4. The element that triggered the event

It is the element where the event happened.

What does { once: true } do?

  1. Runs the handler only one time
  2. Runs it twice
  3. Disables the button
  4. Removes the element

The listener removes itself after firing.

Summary

  • addEventListener(event, handler) connects behaviour.
  • The event object describes what happened.
  • preventDefault stops the browser’s default action.
  • Pass the function itself, not its result.

Next lesson

Next: forms and validation, checking what visitors type.

Questions

Why does my button do nothing?

Check the element was found (not null), the event name is spelled correctly, and you passed the function without brackets.

click vs onclick?

addEventListener allows many handlers and keeps JavaScript out of HTML. onclick allows only one.

What is a callback?

A function passed to another function to be run later, like an event handler.

Progress is saved in this browser.