DevPath · Learn to code ESPTEN

The DOM and Events

Events and forms

Events

A page is interactive because it reacts to actions: clicks, keys, form submissions... Each action is called an event. To respond to an event you register a listener with addEventListener:

const button = document.querySelector("#submit");
button.addEventListener("click", function (event) {
  console.log("Click!");
});

The first argument is the name of the event ("click", "keydown", "submit", "input"...). The second is the handler function, which receives an event object with information about what happened.

Create and remove elements

const li = document.createElement("li"); // create
li.textContent = "New task";
list.appendChild(li);                     // insert
li.remove();                              // remove

Forms

When submitting a form, the browser reloads the page by default. To avoid it and handle it with JavaScript you use event.preventDefault():

form.addEventListener("submit", function (event) {
  event.preventDefault();          // do not reload the page
  const value = input.value;       // read what was typed
  console.log("Submitted:", value);
});

In the exercises of this module you will use the editor's practice document: you will create elements, insert them into document.body, select them and react to events like click — just like in a real browser.

Examples

Generate a <li> list from an array (pure logic)

function listHTML(items) {
  return items.map((t) => `<li>${t}</li>`).join("");
}
console.log(listHTML(["one", "two", "three"]));
Put this into practice

DevPath is a hands-on course: you read the theory here; in the app you put it into practice with exercises that really run, offline.

Start free in the app →
← Select and modify elementsView the module →