event.target, event.key & preventDefault

Use the event object

Lesson 6 of 20 · 11 min · Module 2: Respond to people

Every listener receives an event object describing what happened: which element was involved, which key was pressed, and what the browser is about to do by default. With it, one small function can handle many situations.

Start this lesson →

Free. No installation: you write and run the code in your browser, and it is checked automatically.

By the end, you’ll be able to…

  • Read details from the event object
  • React to specific keys
  • Stop default browser behaviour with preventDefault

The idea

event.target is the element where the event started, so event.target.value is the current text of an input. In a keydown listener, event.key names the key, such as 'Escape' or 'Enter'. event.preventDefault() stops the browser’s default action, such as following a link.

input.addEventListener('keydown', event => {
  if (event.key === 'Enter') console.log('Searching for', event.target.value);
});

01target versus currentTarget

event.target is where the event started; event.currentTarget is the element whose listener is running. They differ when you click a <span> inside a button: target is the span, currentTarget the button.

02Keys have names

event.key gives readable names such as 'Escape', 'Enter', 'ArrowDown' or the character typed. Avoid the old keyCode numbers, which are hard to read and deprecated.

document.addEventListener('keydown', event => console.log(event.key));
// press Escape, then a
Output
Escape
a

03Defaults you can cancel

Links navigate, forms submit and some keys scroll the page. preventDefault() cancels that one default action; the rest of your listener still runs. Only cancel defaults you replace with something better.

Your turn

1) On every input event in #search, show the length of the text in #count, such as 5 / 20 (the 20 comes from the field’s maxLength). 2) In a keydown listener, when the key is Escape, clear the field and update the counter. 3) Clicking #help-link shows or hides #help by toggling its hidden property, and calls preventDefault() so the address does not change.

What the checks look for

  • Typing updates the counter
  • Escape clears the field and the counter
  • Other keys do not clear it
  • The link opens the help panel
  • The link does not change the address
  • A second click closes the panel
Try it in the editor →

Take this with you

The event object tells you what happened and lets you change what happens next.

Go a little further

Turn the counter red with a class when fewer than 5 characters are left.

Learn JavaScript in the Browser for free

20 short lessons with real code and instant checks.

See the whole course →