Summary

In this lesson, you learned that:

  • A handler gets the event object as its argument: function (event) { ... }. event.target is 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" is element.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 gives null.
  • The event input comes after every change of a field's text, so the page can react while the user types. change comes when a choice changes: the value of a select, or the checked of a checkbox (true or false).
  • Text has the methods includes(), toLowerCase() and trim(), which removes the spaces at the start and the end.
  • keydown comes with every key pressed, and event.key says which one: "a", "Enter", "Escape", with capitals just as written.
  • A form is sent with its submit button or with Enter, and then it gets submit. Call event.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().

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

Back

10/10

Next