Nyx

Chapter 5 · Basics

Events

An event is something that happens on the page: a click, a key press, typing in a box. In this chapter you'll learn how to run your code when events happen, how to work with forms and keys, and how to highlight the active item in a menu.

What is an event?

Every time a visitor does something, the browser announces it: "this button was clicked", "a key was pressed in this box". Each announcement is an event, and it has a name. These are the ones you'll use most:

EventHappens when
clickThe element is clicked, or tapped on a phone.
dblclickIt's double-clicked.
inputThe text in a box changes. Happens on every key press.
changeA dropdown, checkbox or radio is changed, or a text box is changed and then left.
submitA form is sent, by pressing its submit button or Enter.
keydownA key is pressed down.
keyupA key is let go.
focusA box is clicked into, or reached with the Tab key.
blurThe visitor leaves a box.
mouseenterThe mouse pointer moves onto the element.
mouseleaveThe mouse pointer moves off it.
scrollThe page, or a box, is scrolled.
resizeThe browser window changes size. Listen on nyx(window).
copyThe visitor copies something.
pasteThe visitor pastes something.

If you mistype an event name, like "clik", Nyx notices and suggests the right one.

Listening with .on()

You met .on() in Chapter 1. It tells Nyx: when this event happens on these elements, run this code. Running code in response to an event is called listening for it.

nyx("#e-like")On this element .on("click",when this happens () => { ... }run this code );Done

Likes: 0

  1. let likes = 0;A variable that starts at 0. We use let instead of const because its value will change.
  2. likes = likes + 1;On each click, add 1 to it.
  3. nyx("#e-likes").text(likes);Show the new number on the page.

Press Run, then click Like a few times. The code inside { } runs once for every click.

Which element was used?

When you listen on many elements at once, like every button with a class, your code needs to know which one was clicked. Nyx hands your function two things:

nyx(".e-size").on("click", (event, button) => {
  nyx("#e-chosen").text("You chose " + button.text());
});
  1. eventDetails about what happened, like which key was pressed. You'll use it in .
  2. buttonThe element that was clicked, already wrapped in Nyx, so you can use .text(), .addClass() and every other method on it straight away.

Choose a size.

You can name the two values anything you like, as long as the order stays the same: the event first, then the element. If you don't need the event, you still have to write a name for it, so many people write (e, button).

What's inside event?

Most of the time you only need the element. But event carries extra details about what happened. These are the ones beginners use:

event.typeThe event's name: "click", "input", "keydown"…
event.keyFor key events: which key was pressed, like "Enter" or "a".
event.dataFor input events: the character just typed, like "e".
event.targetThe exact element the visitor touched. For a click on a <b> inside a button, this is the <b>, while the element Nyx gives you is the button.
event.preventDefault()Stop the browser's normal action, like a form reloading the page. See .

Press Run, then type a few letters. Each line in the Output is one event. Change "input" to "keydown" or "click" and see how the details change.

Typing and choosing

The input event happens every time the text in a box changes, so it's perfect for updating the page while someone types:

5 / 100

.length gives the number of characters in a piece of text. Press Run, then type in the box. We don't use event here: it's only there because box always comes second.

For dropdowns and checkboxes, use the change event. It happens once the choice is made:

Pick a subject.

Forms

When a form is sent, the browser normally loads a new page. Most of the time you want to handle the form with your own code instead, without leaving the page. To stop the browser's normal action, call event.preventDefault():

  1. .on("submit", ...)Listen on the form, not the button. That way pressing Enter in a box works too.
  2. event.preventDefault();"Don't do what you'd normally do": the browser doesn't leave the page.
  3. form.find("[name=name]")Find the box inside this form. .find() searches inside an element.
Don't forget preventDefault on your own pages

Without it, the form sends and the page reloads, so your message flashes for a moment and disappears. (Examples on this site are protected from that, so you can't lose your place.)

Instead of event.preventDefault(), you can also return false; at the end of your function. It does the same thing. Later, Form rules shows how to check fields, and Servers and AJAX shows how to send them.

Keys

To react to one particular key, use .key() with the key's name:

    Common key names:

    "Enter"The Enter (Return) key.
    "Escape"The Esc key. Great for closing pop-ups.
    "Space"The space bar.
    "Tab"The Tab key.
    "Backspace"The key that deletes to the left.
    "Delete"The key that deletes to the right.
    "ArrowUp"The up arrow. Also "ArrowDown", "ArrowLeft" and "ArrowRight".
    "a"A letter or number key: just the character itself, like "a" or "7".

    To find out which key was pressed, listen for keydown and read event.key:

    …

    To listen for a key anywhere on the page, use nyx(document).key("Escape", ...). For shortcuts like Ctrl + K, see nyx.shortcut() in Helpers.

    Mouse over and out

    .hover() takes two functions: one for when the pointer moves onto the element, and one for when it moves off.

    Hover over me

    Phones and tablets have no mouse pointer, so don't hide anything important behind .hover(). Use click for things everyone needs.

    Items added later

    Here's a surprise that catches everyone. A listener only sticks to the elements that exist at the moment you add it. Items you add to the page afterwards don't get it:

    New items don't respond

    nyx("#e-list li").on("click", (e, item) => {
      item.toggleClass("v-done");
    });

    Only the items on the page right now get the listener.

    Every item responds

    nyx("#e-list").on("click", "li", (e, item) => {
      item.toggleClass("v-done");
    });

    Listen on the list, and name the children in the middle.

    The second version listens on the list itself, which never changes. When a click happens inside it, Nyx checks whether it landed on an li, and hands you that li. This trick is called event delegation.

    • Revise maths
    • Write essay

    Press Run, add a few tasks, then click any of them. The new ones work too.

    The active item in a menu

    Menus, tabs and lists often show one item as "active", with a different colour. When a new item is clicked, it becomes active and the old one stops being active. Nyx has three methods for this.

    .picker("li", "active")Set up a whole menu: clicking any item makes it active. Items added later work too.
    .pick("active")Make one item active, and take the class off the items next to it.
    .markCurrent("active")When the page opens, mark the link to the page you're on.

    In all three, the class name is optional. If you leave it out, Nyx uses "active".

    A clickable menu: .picker()

    • Home
    • Courses
    • Results
    • Contact

    Showing: Home

    1. nyx("#e-tabs").picker("li");Clicking any li inside #e-tabs gives it the class active, and takes it off the others.
    2. .on("click", "li", ...)Your own code for what else should happen, like showing the right content.

    The class does nothing until your CSS says how an active item looks:

    .e-menu li.active {
      color: white;
      background: #007aff;
    }

    One item at a time: .pick()

    Use .pick() inside your own code, when you decide which item to make active:

    // Make the third tab active when the page opens
    nyx("#e-tabs li").eq(2).pick("active");

    The page you're on: .markCurrent()

    In a website's main menu, the link to the current page is usually highlighted, so visitors know where they are. .markCurrent() compares each link with the page's address and marks the one that matches:

    <nav id="main-menu">
      <a href="/">Home</a>
      <a href="/courses.html">Courses</a>
      <a href="/contact.html">Contact</a>
    </nav>
    nyx("#main-menu a").markCurrent();

    On the Courses page, the Courses link gets the class active. Put this line on every page, and each page highlights its own link. Nyx takes care of the tricky details:

    Home page/ and /index.html both count as Home.
    Pages inside a sectionOn /blog/my-first-post, the /blog link stays marked.
    Links to sectionsA link like #contact is marked only when the address ends in #contact.
    Other websitesLinks to other websites are never marked.

    Here's a real example. These links point to chapters of this guide, and you're on the Events chapter right now:

    Here we selected the li items, so the class goes on the li. Select the links ("#e-chapters a") to put it on the links instead.

    Kind to screen readers

    All three methods also set aria-current, a hidden label that tells screen readers which item is the active one. You get this for free.

    Once, off and trigger

    .once("click", fn)Listen only for the first time. After that, the listener removes itself.
    .off("click")Stop listening: removes every click listener you added with Nyx.
    .off("click", fn)Remove just one listener. Pass the same function you gave to .on().
    .trigger("click")Make the event happen from code, as if the visitor did it.

    Only the first click counts. To use .off() with one function, give the function a name first: const sayHi = () => { ... };, then .on("click", sayHi) and later .off("click", sayHi).

    Putting it together

    A small quiz: click an answer to check it. It uses event delegation, the element Nyx hands you, and classes.

    Which planet is closest to the Sun?

    • Venus
    • Mercury
    • Mars

    Click an answer.

    1. nyx("#e-quiz").on("click", "li", ...)Listen on the list, and react to clicks on any answer.
    2. answer.pick("active");Highlight the chosen answer, and only that one.
    3. if (answer.text() === "Mercury") { ... } else { ... }If the text is exactly Mercury, run the first block. Otherwise run the second.
    4. answer.bounce(); A little animation. You'll meet more in Animation.

    Common mistakes

    MistakeFix
    .on("click", sayHi())The brackets run sayHi straight away, once. Pass the function itself: .on("click", sayHi).
    .on("clik", ...)A typo in the event name. Nyx warns you and suggests "click".
    .on("click")No function, so there's nothing to run. Nyx tells you to add one.
    Listening before the element existsWrap your code in nyx(() => { ... }) so it waits for the page, as in Chapter 1.
    New items don't respondUse event delegation: nyx("#list").on("click", "li", fn).
    The form reloads the pageAdd event.preventDefault(); as the first line inside your submit listener.

    Good to know

    .on("input change", fn)Listen for several events at once by separating their names with spaces.
    .trigger("cart:updated", { count: 3 })Make up your own event and send it with data. Read the data as event.detail.
    .focus()Put the typing cursor in a box, ready for the visitor to type.
    .appear(fn)Run code once an element scrolls into view. See Helpers.

    Exercise

    Fill in the blanks, then press Check answers.

    1. Run code when #save is clicked.

    nyx("#save").("click", () => { ... });

    2. Update the page while someone types in #search.

    nyx("#search").on("", () => { ... });

    3. Stop a form from reloading the page.

    nyx("#form").on("submit", (event) => {
      event.();
    });

    4. Run code when Enter is pressed in #chat.

    nyx("#chat").key("", () => { ... });

    5. React to clicks on every li in #list, even ones added later.

    nyx("#list").on("click", "", (event, item) => { ... });

    6. Make clicked items in #nav active.

    nyx("#nav").("li");

    Remember

    .on("event", (event, item) => { ... }) runs code when an event happens.
    item is the element that was used, ready for Nyx methods.
    input for typing, change for choices, submit for forms.
    Call event.preventDefault() to stop a form reloading the page.
    .key("Enter", fn) reacts to one key.
    For items added later, listen on the parent: .on("click", "li", fn).
    .picker(), .pick() and .markCurrent() handle the active item in a menu.