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 intodocument.body, select them and react to events likeclick— 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"]));