Summary
In this lesson, you learned that:
- A handler gets the event object as its argument:
function (event) { ... }.event.targetis the element where the event happened, so one function can handle several elements. - Attributes that start with
data-keep your own data in elements:data-color="teal"iselement.dataset.color, always as text. - Events bubble up through the elements that the target is in, so one handler on a list handles clicks on all its items, even ones added later.
event.target.closest("li")finds the clicked item, or givesnull. - The event
inputcomes after every change of a field's text, so the page can react while the user types.changecomes when a choice changes: thevalueof aselect, or thecheckedof a checkbox (trueorfalse). - Text has the methods
includes(),toLowerCase()andtrim(), which removes the spaces at the start and the end. keydowncomes with every key pressed, andevent.keysays which one:"a","Enter","Escape", with capitals just as written.- A
formis sent with its submit button or with Enter, and then it getssubmit. Callevent.preventDefault()in the handler, or the browser loads the page again, and everything typed is gone. - Before you use what was typed, check it: empty, too short, not a number (
Number.isNaN(), never=== NaN). Show each error next to its field, empty it once the field is right, and do the form's job only when every field is right.
In the next lesson, Checkpoint: Sign-Up Form, you'll put all of this to work in a sign-up form that checks itself: it says what's wrong, field by field, and welcomes the new user when everything is right.
But first, a little practice: a sticky note that you can write on and color. script.js is empty again, and you'll write the whole program yourself.
Instructions
Make the note show what's written in the field #text as you type: after every change of the field's text, put the text into #note.
A click on a button in #colors changes the background color of #note (its style.backgroundColor) to the color in the button's data-color. The buttons have no id, so give #colors one click handler, and find the clicked button with closest().