Register to get access to free programming courses with interactive exercises

Introduction to events JS: DOM API

Interactive systems, such as websites in a browser or even the terminal, are arranged according to the same principle. After loading, they go into a waiting mode, where they wait for the user to perform an action. These actions include clicks, typing, moving the mouse, keyboard shortcuts, and other things.

From the code's perspective, all actions are represented by events. Some of them are:

  • click
  • submit
  • keyup/keydown
  • focus
  • contextmenu
  • mouseover
  • mousedown/mouseup

The events are highly detailed, even typing a letter is split into two events: pressing the key and releasing the key. In addition, there is a special keypress, event that allows you to distinguish hotkeys from normal input.

Any event will be associated with a specific element in the DOM. To add a new behavior, you need to find an element and add a callback to the addEventListener() method, which will be called when an event occurs:

<button id="myButton"></button>
const button = document.getElementById('myButton');

// Adding a handler that will be called when a button element is clicked
button.addEventListener('click', () => alert('Boom 1!'));

// Adding a second handler
button.addEventListener('click', () => alert('Boom 2!'));

Each event handler is a function that will be called when the event occurs. The handlers are called one after the other, in the same order in which they were defined.

If necessary, you can delete the handler, although this is rarely done in practice:

const button = document.getElementById('myButton');

const handler = () => alert('Boom 1!');
button.addEventListener('click', handler);

// It's important to pass the exact same function here (by reference)
button.removeEventListener('click', handler);

Events can be called programmatically. For example, this is relevant for focus. Imagine that you open a chat hoping to write a message there, but no text appears. To type, you need to focus on the input field. By default, this doesn't happen, and this is where we come in:

const input = document.getElementById('textInput');
// The cursor appears in the input field
// Try changing channel in Slack,
// you will see that the input field is focused on automatically
input.focus();

How to test

If you want to get a good understanding of how events work, you need to regularly practice with them in the browser. The easiest way to do this is as follows:

  1. Open the console on any site. See where you can find the kind of elements you want to work with, such as buttons or forms
  2. Choose any element you want to practice with. For simplicity's sake, you can take body
  3. Add a handler to it
  4. Call an event and you'll see a reaction
const element = document.body;
element.addEventListener('click', () => console.log('wow!'));
// Now you can click on any part of the site
wow!

// If you need a form element

// Selects the first input it encounters
const element2 = document.querySelector('input');
// Here we hang the handler and display everything we need
element2.addEventListener('keyup', () => console.log('pressed!'));

This is how you can test any event on any site.

Event object

Each event that occurs has information associated with it, which depends on the type of event. For example, the click event doesn't just involve the click itself, but also the coordinates of the point on the screen where the click was made. This information is available through a special event object passed to the event handler. Event objects will always be passed to any handler as a single parameter.

<div id="myElement">Boom!</div>
const button = document.getElementById('myElement');

button.addEventListener('click', (event) => {
  // Regular object
  console.log(event);
  // Coordinates of the point where the click occurred
  console.log(event.clientX);
  console.log(event.clientY);
});

Each click on the button will cause a new event object to be created with its own values that correspond to the current event. event is an ordinary object filled with a large number of properties that are most easily studied in the browser itself. Different events have both common properties and specific ones, for example, a click has coordinates, and a keystroke has its value. For more information about the properties, see the documentation.

General properties:

  • event.target - the DOM element where the event occurred. It's the easiest way to get to the data that may be needed after the event.
  • event.type is the name of the event, for example click, keyup, and so on.

As an example, let's look at the task of validating the entered password. We'll highlight the input field with a red frame if the password is too short.

See the Pen js_dom_events by Hexlet (@hexlet) on CodePen.

Default action

For some elements, the browser performs a default action when certain events are triggered. For example, if we put a handler for clicking on a link, it will suddenly take us to another page, the one specified in the href attribute. Here we can see an example of the default action itself, which isn't affected by the presence of handlers in any way. If you cancel this action, and you need to quite often, you need to call the event.preventDefault() method inside the handler.

<a href="#" id="myElement">Boom!</a>
const button = document.getElementById('myElement');

button.addEventListener('click', (e) => {
  // If this isn't done, the browser will load a new page
  e.preventDefault();
  alert(e.target.textContent);
});

The following elements have default actions:

  • Clicking on a link takes you to the page specified in the href attribute
  • Clicking a submit button starts sending the form to the server
  • Rotating the mouse wheel in textarea moves the text if it doesn't fit
  • Right-click context menu call

Competition between events

While handlers are being executed, new events may occur both from user actions and automated actions from the handlers themselves, and some events always occur as a whole block, for example, mouseup and click. But this doesn't mean that the execution of the code will automatically drop everything and switch over to processing these events Instead, events are queued and executed sequentially.

But some events are still taken into processing immediately. This applies to events that are generated programmatically, for example focus.

You may be wondering what happens to the page while the handler is being executed. And there are a few possible options here. If the handler executes some code synchronously, such as making calculations, then at this moment everything else will be blocked and the page will freeze. If this behavior lasts too long, then some browsers will freeze, and others will suggest closing the tab. Here we can conclude that handlers should perform their task as quickly as possible. But what if we have a synchronous tab, such as a request being made to the server? In this case, everything continues to work fine, since HTTP requests do not block code execution.

This lesson may make it clear why JavaScript is the way it is. The event system is possible only in asynchronous code. Essentially, when a page loads, the handlers are initialized and installed, and then, as a rule, no code is executed; the entire page waits for actions from the user.

Common mistakes

Quite often, beginners get confused about functions and instead of the function itself, they pass the result of the function call to the handler:

const button = document.getElementById('myElement');
const handler = () => {
  alert('Click!');
};

button.addEventListener('click', handler());

The handler() function is executed when the handler is hovered over the event, instead of the function itself the result of the handler() call will be passed.


Hexlet Experts

Are there any more questions? Ask them in the Discussion section.

The Hexlet support team or other students will answer you.

About Hexlet learning process

For full access to the course you need a professional subscription.

A professional subscription will give you full access to all Hexlet courses, projects and lifetime access to the theory of lessons learned. You can cancel your subscription at any time.

Get access
130
courses
1000
exercises
2000+
hours of theory
3200
tests

Sign up

Programming courses for beginners and experienced developers. Start training for free

  • 130 courses, 2000+ hours of theory
  • 1000 practical tasks in a browser
  • 360 000 students
By sending this form, you agree to our Personal Policy and Service Conditions

Our graduates work in companies:

<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.bookmate">Bookmate</span>
<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.healthsamurai">Healthsamurai</span>
<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.dualboot">Dualboot</span>
<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.abbyy">Abbyy</span>
Suggested learning programs

From a novice to a developer. Get a job or your money back!

Frontend Developer icon
Profession
beginner
Development of front-end components for web applications
start anytime 10 months

Use Hexlet to the fullest extent!

  • Ask questions about the lesson
  • Test your knowledge in quizzes
  • Practice in your browser
  • Track your progress

Sign up or sign in

By sending this form, you agree to our Personal Policy and Service Conditions
Toto Image

Ask questions if you want to discuss a theory or an exercise. Hexlet Support Team and experienced community members can help find answers and solve a problem.