Nyx

Chapter 16 · Beyond the DOM

Everyday helpers

Real websites keep needing the same small features: a "Saved!" message, a Copy button, keyboard shortcuts, a warning when the internet drops. Each one takes a page of plain JavaScript. In this chapter you'll learn Nyx's one-line versions of seven of them.

Small messages: nyx.toast

A toast is a small message that pops up in the corner of the screen, then disappears by itself, like toast popping out of a toaster. It's perfect for "Saved!", "Copied!" or "Message sent". Click the buttons, and look at the bottom-right corner of your screen:

nyx.toast(pop up "Saved!",this message "success",type (optional) "6 seconds"how long (optional) )Done
TypeUse it for
"info"Plain news. This is the type if you don't give one.
"success"Something worked: saved, sent, copied.
"warn"Something to be careful about.
"error"Something failed. Screen readers announce error toasts straight away.

Toasts stay for 3 seconds unless you give a time, written as in Timers and delays. Use them for short news only: a problem that someone must fix, like a wrong email, belongs next to its field, as in Checking forms.

Copy buttons: nyx.copy

nyx.copy() puts text on the clipboard, ready to paste. It gives back true if it worked, so use await, as in Servers and AJAX:

Your coupon code: SCHOOL25

  • Copy after a click. Browsers only allow copying when the visitor has just clicked or pressed a key, so people can't have their clipboard changed behind their back.
  • Lists and objects are copied as neat JSON text, which is handy for sharing data.
  • Copying an element doesn't work: copy its text, as above with .text().

Reading aloud: nyx.say

nyx.say() reads text aloud using the voice built into the visitor's device. It helps people who find reading hard, and it's great for spelling games and language lessons. Turn your sound on and click Read:

Twinkle, twinkle, little star. How I wonder what you are.

OptionWhat it does
rate: 1Speed. 0.5 is half speed, 2 is double.
pitch: 1How high the voice is, from 0 to 2.
lang: "hi-IN"The language, as a locale code from Formatting: "en-IN", "hi-IN", "bn-IN"... Which voices exist depends on the device.
  1. speech = nyx.say(...)Start reading, and keep the speech in a variable.
  2. await speech;Wait until the reading has finished, then carry on.
  3. speech.stop()Stop reading early, like the timers' .stop().

Starting a new nyx.say() stops the one before, so voices never talk over each other.

Keyboard shortcuts: nyx.shortcut

Shortcuts let people work without the mouse. This website has one: press Ctrl+K (⌘+K on a Mac) and the sidebar search opens. It's made with nyx.shortcut("mod+k", ...).

Write the keys joined with +, and the function to run. Click on the page outside the box, then press / or Alt+S to jump to the search box, and Esc to clear it:

WriteMeans
"mod"Ctrl on Windows and Linux, ⌘ on a Mac. Use this, so your shortcut feels right on every computer.
"ctrl", "cmd"Exactly Ctrl, or exactly ⌘. "control" and "command" work too.
"shift", "alt"Shift and Alt ("option" on a Mac).
Letters and digits"k", "7": always small letters, even with Shift.
Named keys"esc", "enter", "space", "tab", "up", "down", "left", "right", "delete", "backspace"
Symbols"/", "?", "." and so on: the symbol itself.
  • Single keys wait while people type. A shortcut like "/" doesn't fire inside a text box, so people can still type a slash. Esc is the exception, because it means "cancel" everywhere. Shortcuts with Ctrl, ⌘ or Alt work everywhere too.
  • Some browser shortcuts can't be replaced, like Ctrl+W (close tab) or Ctrl+T (new tab). Choose keys the browser doesn't use.
  • Tell people about your shortcuts, for example in a placeholder or with <kbd> tags, or nobody will know they exist.
  • nyx.shortcut() gives back an object with .stop(), to turn the shortcut off again.

Online or offline: nyx.online

nyx.online() runs your function straight away with true or false, and again whenever the connection changes. Show a banner when it drops:

To try it, open the developer tools (F12), choose the Network tab, and change No throttling to Offline. Then set it back. "Online" means the device is connected to a network; it can't promise that every website is reachable.

Bar charts: nyx.chart

nyx.chart() draws a bar chart inside an element, from an object of names and numbers:

OptionWhat it does
formatA function that writes each number next to its bar. Use (v) => nyx.money(v, "INR") for money. Numbers get separators if you don't give one.
colorThe bars' colour: any CSS colour. If you don't give one, bars are the colour of the text.

Draw the chart again whenever the data changes. With a smart state from Saving data and smart state, .watch() does that for you:

The chart describes itself for screen readers too, like "Bar chart: Football 4, Cricket 6, Chess 2". Every value must be a number: text from an input needs Number() first.

When something scrolls into view: .appear

.appear() runs your function once, the first time an element scrolls into view. Use it to reveal cards as people reach them, or to start something only when it can be seen. Scroll down inside the box:

Scroll down ↓

Maths club: Monday
Art club: Tuesday
Science club: Wednesday
Music club: Thursday
Drama club: Friday

Seen: 0

The function gets each element as it appears, ready for any Nyx method. Each element counts once: scrolling back up doesn't run it again.

Putting it together

A "Word of the day" card. Copy the word with a button or the C key, hear it with Listen, and see a warning if the internet drops:

Serendipity

Finding something good without looking for it.

  1. async function copyWord()One function for both the button and the shortcut, so they always do the same thing.
  2. nyx.shortcut("c", copyWord)Pressing C copies too, except while someone is typing in a box.
  3. nyx(".he-word p").last()The meaning is the card's last paragraph, from Finding elements.

Common mistakes

MistakeFix
Copying when the page loadsBrowsers block it. Copy inside a click or key listener.
Forgetting await with nyx.copy()Without it you get a promise, not true or false.
Silence from nyx.say()Check the sound is on. Some browsers only speak after the visitor has clicked something.
A shortcut that never firesThe browser may own it (like Ctrl+T), or the focus is inside a text box for a single-key shortcut.
Toasts for problems that need fixingThey disappear. Show those messages next to the field instead.
A chart that doesn't updateDraw it again after every change, for example inside .watch().
Text values in a chartTurn them into numbers with Number() first.

Exercise

Fill in the blanks, then press Check answers.

1. Show a green "Saved!" message in the corner.

nyx.toast("Saved!", "");

2. Copy the text, and wait for the answer.

const ok =  nyx.copy("SCHOOL25");

3. Read a sentence aloud, slowly.

nyx.say("Good morning", { : 0.75 });

4. Ctrl+S on Windows, ⌘+S on a Mac.

nyx.shortcut("", save);

5. Know when the internet drops or returns.

nyx.((online) => nyx("#banner").toggle(!online));

6. Draw a bar chart of the votes.

nyx.("#votes", { Yes: 12, No: 5 });

7. Fade each photo in when it scrolls into view.

nyx(".photo").((photo) => photo.fadeIn());

Remember

nyx.toast(message, type) shows short news in the corner: info, success, warn or error.
await nyx.copy(text) copies, inside a click, and tells you if it worked.
nyx.say(text) reads aloud. await it to wait; .stop() stops it.
nyx.shortcut("mod+k", fn) adds a shortcut. mod is Ctrl or ⌘; single keys wait while people type.
nyx.online(fn) tells you when the connection drops or returns.
nyx.chart(element, data) draws bars from names and numbers. .appear(fn) runs once when something scrolls into view.