Nyx

Chapter 1 · Basics

Getting started

In this chapter you'll learn what Nyx is, add it to a web page, and write your first lines of Nyx code. You don't need any experience with JavaScript.

Install Nyx

Paste this before your own scripts. It loads Nyx from jsDelivr, a free CDN:

<script src="https://cdn.jsdelivr.net/gh/chiranjit2020/nyx@0.3.0/nyx.min.js"
        integrity="sha384-IBYiJCeK9gKhsps2iIHXSKCMSoxAABysWko3Dst/7uP1+44LvSJeCK7O2+M3O5iJ"
        crossorigin="anonymous"></script>

Or use npm, if your project has a build tool. Then write import nyx from "nyx-dom"; in your code:

npm install nyx-dom

Or load the same file from unpkg. You only need one of the three:

<script src="https://unpkg.com/nyx-dom@0.3.0/nyx.min.js"
        integrity="sha384-IBYiJCeK9gKhsps2iIHXSKCMSoxAABysWko3Dst/7uP1+44LvSJeCK7O2+M3O5iJ"
        crossorigin="anonymous"></script>

New to all this? Don't worry about these yet. Start with , and we'll build your first page step by step.

What is Nyx?

A web page is built from three things:

HTMLThe content: headings, paragraphs, buttons, images.
CSSThe look: colours, sizes, spacing.
JavaScriptThe behaviour: what happens when you click, type or scroll.

Nyx is a JavaScript library. A library is a file of ready-made code that someone else wrote, so you don't have to. With Nyx, jobs that take many lines of plain JavaScript take one short line.

For example, to change the text of a heading:

Plain JavaScript

document.querySelector("#title").textContent = "Hello";

With Nyx

nyx("#title").text("Hello");

Both lines do exactly the same thing. The Nyx version is shorter and reads almost like English: find #title, set its text to Hello.

Nyx also helps you when you make a mistake. Instead of silently doing nothing, it tells you what went wrong and how to fix it. You'll see this later in the chapter.

Before you start

What you should know first

You should know a little HTML: what a tag is, and how to write a heading, a paragraph and a button. If you can read <button id="save">Save</button> and understand it, you're ready.

These words appear a lot in this guide. You don't need to memorise them; come back here whenever you need to.

ElementOne piece of a page, made by a tag. <h1>Hi</h1> is a heading element.
idA unique name you give one element: <h1 id="title">. Only one element on a page should have each id.
classA group name that many elements can share: <p class="tip">.
SelectorA short code that tells Nyx which elements you mean: #title means "the element with id title".
MethodAn action you ask Nyx to do, like .text() or .hide(). It always has round brackets.
StringText inside quotes, like "Hello". The quotes tell JavaScript it's text, not code.
FunctionA block of code saved to run later. In Nyx you'll mostly write them as () => { ... }.

Your first Nyx page

Let's build a real page on your computer. You need a text editor (like VS Code or Notepad) and a web browser (like Chrome).

Step 1: Download Nyx

  1. Open github.com/chiranjit2020/nyx.
  2. Click the file nyx.js, then click the Download raw file button (the arrow pointing down).
  3. Make a new folder on your computer called my-first-nyx and put nyx.js inside it.

Don't want to download anything? You can load Nyx straight from the internet with one line instead. See at the top of this page.

Step 2: Create the page

In the same folder, create a file called index.html. Your folder should now look like this:

my-first-nyx/
├── index.html
└── nyx.js

Open index.html in your editor and type (or copy) this:

<!DOCTYPE html>
<html>
<head>
  <title>My first Nyx page</title>
</head>
<body>

  <h1 id="title">Hello</h1>

  <script src="nyx.js"></script>
  <script>
    nyx("#title").text("Hello, Nyx!");
  </script>

</body>
</html>

What each part does

  1. <h1 id="title">Hello</h1>A normal heading. We gave it the id title so Nyx can find it.
  2. <script src="nyx.js"></script>Loads the Nyx library from the file next to your page. This line must come before any Nyx code.
  3. <script> ... </script>Your own JavaScript goes between these tags.
  4. nyx("#title").text("Hello, Nyx!");Finds the element with id title and changes its text.
Why are the scripts at the bottom?

The browser reads your page from top to bottom. Putting scripts just before </body> means the heading already exists when your code runs. There's another way to handle this, explained in .

Step 3: Open it

Double-click index.html to open it in your browser. You should see a big heading that says Hello, Nyx!. The page said "Hello", and Nyx changed it the moment the page opened.

You can try the same thing right here, without making any files:

Hello

Change "Hello, Nyx!" to your own name and press Run.

How the Try it Yourself boxes work

You'll find a box like this in every chapter. Here's everything it can do:

HTMLAt the top left: the HTML of the example's little page. Read it to see the ids and classes your selectors point to. You can't change it here.
JavaScriptBelow the HTML: the code. You can change any of it. It's your own copy, so you can't break anything.
RunRuns your code. You can also press Ctrl Enter (⌘ Enter on a Mac) while typing in the code.
ResetPuts the original code and example back, if you want to start again.
The exampleOn the right, at the top: a small piece of page for your code to work on. It starts fresh every time you press Run.
OutputUnderneath the example. Shows Nyx's messages, mistakes in your code, and anything you print().

print(): seeing a value

Sometimes you want to see a value rather than change the page: how many items Nyx found, or what someone typed. Inside these boxes, print() writes it in the Output:

Nyx is fun

  1. print("Hello from print!");Shows a piece of text.
  2. print("The text is:", ...)Give it several values, separated by commas, and it shows them on one line with spaces between.
  3. print("2 + 3 =", 2 + 3);It works out sums and anything else first, then shows the answer: 2 + 3 = 5.

print() also understands things that are hard to show as text. A Nyx result shows as nyx(2 elements): <p>, <p>, and an event shows its useful details. You'll see this in later chapters.

print() only works on this website

print() isn't part of Nyx or JavaScript. It's a helper built into these boxes so you don't have to open the console. On your own pages, use console.log() instead. It takes the same values, like console.log("The text is:", nyx("#title").text());, and shows them in the browser's console. You'll learn how to open the console .

What's aria-label?

In some examples' HTML you'll see aria-label="...". It's a name for screen readers, the tools that read pages aloud for people who can't see the screen. It doesn't change how anything looks or works, so you can ignore it while learning. It's a good habit to keep it in your own pages, though.

Each box only looks inside itself

On a real page, nyx("p") finds every paragraph on the whole page. In these boxes, it only searches the example above the Output, so your code can't change the rest of this guide.

How the CDN link works

Instead of downloading nyx.js, you can load it from a CDN (Content Delivery Network): a free service with servers all over the world that send the file quickly to every visitor. Nothing to download, and your folder only needs index.html.

In your page, replace the <script src="nyx.js"> line with the jsDelivr or unpkg code from at the top of this page. Here's what each part of it means:

  1. cdn.jsdelivr.net/gh/chiranjit2020/nyxjsDelivr, a free CDN, serving the file straight from the Nyx project on GitHub. The unpkg link has unpkg.com/nyx-dom here instead, because unpkg serves the file from npm.
  2. @0.3.0The Nyx version. It never changes, so your page keeps working exactly the same until you choose to update.
  3. nyx.min.jsThe minified Nyx: the same code with spaces and comments removed, so it's about half the size. It works exactly like nyx.js, and its messages still point at the line in your file.
  4. integrity="sha384-..."A fingerprint of the file. The browser checks it, and if the file was changed in any way, even by one letter, the browser refuses to run it. This protects your visitors if the CDN is ever hacked.
  5. crossorigin="anonymous"Needed for the fingerprint check to work with a file from another site. It also means no cookies are sent to the CDN.
Copy all three parts together

Each version has its own fingerprint. If you change @0.3.0 to another version, copy that version's new integrity from this page too. Otherwise the browser blocks the file, and the console says it "failed integrity check".

UseWhen
nyx.jsLearning, and working without internet. The file is easy to read if you're curious how Nyx works.
nyx.min.jsReal websites. Smaller, so pages load faster.

How Nyx code is written

Almost every line of Nyx follows the same pattern:

nyxUse Nyx ("#title")Find this .text("Hi")Do this ;End of the line
  1. nyxTells the browser you want to use Nyx.
  2. ("#title")The selector: which element or elements you mean. It's a string, so it goes in quotes.
  3. .text("Hi")The method: what to do with them. The dot joins it to what you found.
  4. ;The semicolon ends the instruction, like a full stop ends a sentence.

The three most common selectors

SelectorMeans
nyx("#title")The element with id="title". # means id.
nyx(".tip")Every element with class="tip". . means class.
nyx("p")Every <p> paragraph. No symbol means a tag name.

The next chapter, Finding elements, covers selectors in detail.

Example: hide every tip

This page has two paragraphs with the class tip. One line hides both of them.

Study tips for exam week:

Tip 1: Sleep 8 hours.

Tip 2: Drink water.

Now try nyx("#intro").hide(); or nyx("p").hide(); and see what disappears.

Making things happen on a click

So far our code runs as soon as the page opens. Most of the time you want code to run when the visitor does something, like clicking a button. That's what .on() is for.

nyx("#change").on("click", () => {
  nyx("#hello").text("You clicked!");
});
  1. nyx("#change")Find the button with id change.
  2. .on("click", ...)When it's clicked, run the code that comes next.
  3. () => { ... }A function: the block of code to run. Everything between { and } waits until the click happens.
  4. nyx("#hello").text("You clicked!");The code that runs on each click.
  5. });Closes the function }, then closes .on( with ), then ends the line with ;.

Hello

Brackets must match

Every ( needs a ) and every { needs a }. Missing one is the most common beginner mistake. If your code stops working, count your brackets first.

Wait for the page to load

Remember that the browser reads the page from top to bottom. If your script is in the <head>, at the top, it runs before the rest of the page exists, so Nyx can't find anything.

Doesn't work

<head>
  <script src="nyx.js"></script>
  <script>
    nyx("#title").text("Hi");
  </script>
</head>
<body>
  <h1 id="title">Hello</h1>
</body>

The code runs before the heading exists.

Works

<head>
  <script src="nyx.js"></script>
  <script>
    nyx(() => {
      nyx("#title").text("Hi");
    });
  </script>
</head>
<body>
  <h1 id="title">Hello</h1>
</body>

The code waits until the page is ready.

When you give nyx() a function instead of a selector, Nyx waits until the whole page has loaded, then runs it.

A good habit

Wrap all your code in nyx(() => { ... });. Then it works no matter where you put your script. If you forget, Nyx notices and tells you in the console.

Doing several things in a row

You can add more methods to the same line, each starting with a dot. This is called chaining. Nyx does them in order, left to right.

nyx("#badge").text("Finished!").css("color", "green").pulse();

This reads: find #badge, set its text to Finished!, make it green, then make it pulse. Long chains are easier to read on separate lines:

Homework: not started

Only the last line has a semicolon, because the whole chain is one instruction.

When something goes wrong

Everyone makes typos. Plain JavaScript and jQuery usually stay silent, which leaves you guessing. Nyx explains the problem in the browser's console, a hidden panel for messages from your code.

How to open the console

Windows (Chrome, Edge)Press F12, then click the Console tab.
Mac (Chrome)Press ⌥ ⌘ J.
Mac (Safari)Turn on Show features for web developers in Settings › Advanced, then press ⌥ ⌘ C.
Any browserRight-click the page, choose Inspect, then open Console.

In the examples on this site, Nyx's messages appear in the Output box instead, so you don't need to open anything. This code has a typo. Run it and read what Nyx says:

Welcome

Fix the typo the way Nyx suggests, then run it again.

Exercise

Fill in the blanks, then press Check answers.

1. Hide the element with id menu.

("#menu").hide();

2. Change the text of the element with id name to Asha.

nyx("#name").("Asha");

3. Find every element with the class card.

nyx("").show();

4. Run code when the button #save is clicked.

nyx("#save").on("", () => {
  nyx.toast("Saved!");
});

Remember

Load Nyx with <script src="nyx.js"></script> before your own code.
Nyx code follows one pattern: nyx("selector").method().
# finds by id, . finds by class, a plain word finds by tag.
.on("click", () => { ... }) runs code when something is clicked.
Wrap your code in nyx(() => { ... }); so it waits for the page.
When something doesn't work, open the console and read Nyx's message.
print() shows values in this website's boxes. On your own pages, use console.log().
Using WordPress?

You don't need to download anything. Install the Nyx plugin and it loads on every page. See WordPress.