Nyx

Chapter 18 · Reference

Coming from jQuery

Many tutorials, WordPress themes and older websites use jQuery, the library Nyx was inspired by. This chapter shows how jQuery code maps to Nyx, what Nyx does differently on purpose, and how to convert jQuery code you find, step by step.

Same ideas, its own style

If you know jQuery, you already know how Nyx thinks: find elements, change them, react to events, animate, talk to servers. Here's the same small feature in both:

jQuery

$(function () {
  $(".like").on("click", function () {
    $(this).addClass("liked");
    $(this).find(".count").text("1");
    $("#note").fadeIn(400).delay(2000).fadeOut();
  });
});

Nyx

nyx(() => {
  nyx(".like").on("click", (event, like) => {
    like.addClass("liked");
    like.find(".count").text("1");
    nyx("#note").fadeIn("400ms").wait("2 seconds").fadeOut();
  });
});

Most lines are nearly the same. The differences are on purpose, to make code easier to read and mistakes easier to find:

  • The name is nyx, not $, so it never clashes with jQuery.
  • Times are words: "2 seconds" instead of 2000.
  • Event handlers get the element ready to use: like.addClass() instead of $(this).addClass().
  • Requests use await and give you the data directly.
  • Nyx explains mistakes. jQuery stays silent when a selector matches nothing.

jQuery and Nyx, side by side

Find the jQuery you know on the left, and its Nyx version on the right. Each group links to its chapter.

Starting and finding (Getting started, Finding elements)

jQueryNyx
$(document).ready(fn), $(fn)nyx(fn)
$("#menu")nyx("#menu")
$("li").lengthnyx("li").count()
if ($("#x").length)if (nyx("#x").exists())
$("li").first(), .last(), .eq(2)The same: .first(), .last(), .eq(2)
$("li")[0], .get(0).get(), or .get(0)
.each(function (i, el) { }).each((item, i) => { }): the order is swapped (see below).

Changing content (Changing content)

jQueryNyx
.text(), .html()The same: .text(), .html()
.val().value()
.attr(), .prop(), .data()The same
.append(), .prepend(), .before(), .after()The same
.remove(), .empty(), .clone(), .replaceWith()The same
$("<li>").text(name)nyx.create("li", { text: name }), which is always safe
$("#f").serialize()nyx("#f").formData(), an object instead of text

Styles and visibility (Styles and visibility)

jQueryNyx
.css(), .addClass(), .removeClass(), .toggleClass(), .hasClass()The same
.show(), .hide(), .toggle()The same, but always instant. For a speed, use .fadeIn() or .slideDown().
.offset()The same
.position().offset()

Dimensions (Dimensions)

jQueryNyx
.width(), .height()The same
.innerWidth(), .innerHeight()The same
.outerWidth(), .outerHeight()The same
.outerWidth(true).fullWidth()
.outerHeight(true).fullHeight()
$(window).width(), $(document).height()The same, with nyx instead of $

Events (Events)

jQueryNyx
.on("click", function (e) { $(this) }).on("click", (event, item) => { item })
.on("click", "li", fn)The same: .on("click", "li", (event, li) => { })
.click(fn).on("click", fn) (.click(fn) works too)
.one().once()
.off(), .trigger(), .hover()The same
.bind(), .live(), .delegate().on()
.keydown(e => { if (e.key === "Enter") ... }).key("Enter", fn)

Moving around (Moving around)

jQueryNyx
.parent(), .parents(), .closest(), .children(), .siblings()The same
.next(), .prev(), .find(), .filter(), .not(), .has(), .is()The same
.end(), .addBack()Keep the first list in a variable instead

Animation (Animation)

jQueryNyx
.fadeOut(400).fadeOut("400ms")
.fadeOut("slow").fadeOut("600ms"). jQuery's "fast" is "200ms".
.fadeOut(400, fn).fadeOut("400ms").done(fn)
.delay(1000).wait("1 second")
.animate({ left: 100 }, 400).animate({ left: "100px" }, "400ms")
.promise().done(fn).done(fn)
.stop()The same: .stop()

AJAX (Servers and AJAX)

jQueryNyx
$.get(url, fn), $.getJSON(url, fn)const data = await nyx.get(url);
$.post(url, data, fn)await nyx.post(url, data, { as: "form" }) (see below)
$.ajax({ url, type, data })await nyx.request({ url, method, data })
.done(fn).fail(fn)try { await ... } catch (error) { }
$("#box").load("page.html #part")The same: nyx("#box").load("page.html #part")
$.ajax({ url: ajaxurl, data: { action } }) in WordPressawait nyx.wp.ajax("action", data), nonce included

Helpers

jQueryNyx, or plain JavaScript
setTimeout(fn, 2000)nyx.after("2 seconds", fn)
$.each(list, fn)list.forEach((item) => { })
$.extend(a, b)Object.assign(a, b)
$.trim(text)text.trim()
$.isArray(x)Array.isArray(x)
$.parseJSON(text)JSON.parse(text)
jQuery.noConflict()Not needed: Nyx never uses $

Event handlers: no more $(this)

In jQuery, the clicked element is this, and you wrap it as $(this) before using it. Nyx gives your function the element already wrapped, as its second value:

jQuery

$(".tab").on("click", function (e) {
  $(this).addClass("active");
});

Needs function, because arrow functions have no this of their own.

Nyx

nyx(".tab").on("click", (event, tab) => {
  tab.addClass("active");
});

Works with arrow functions. Name it after what it is: tab, button, card.

this still works inside a function () { }, as the plain element, so converted code doesn't break straight away. But (event, item) is clearer.

.each(): the order is swapped

The one that catches everyone

jQuery's .each() gives you the position first, then the element: function (i, el). Nyx gives you the item first, already wrapped, then the position: (item, i). The item is what you need most often, so it comes first.

jQuery

$("li").each(function (i, el) {
  $(el).text((i + 1) + ". " + $(el).text());
});

Nyx

nyx("li").each((item, i) => {
  item.text((i + 1) + ". " + item.text());
});

Animation: real times and .done()

jQuery takes speeds like 400, "slow" and "fast", and a function to run afterwards. Nyx takes times written in words, and .done() for what comes next:

jQuery

$("#box").fadeOut("slow", function () {
  $("#msg").show();
});

Nyx

nyx("#box").fadeOut("600ms").done(() => {
  nyx("#msg").show();
});

And .show(), .hide() and .toggle() are always instant in Nyx. They don't take a speed: if you want movement, say which kind with .fadeIn() or .slideDown(). This keeps every method doing one thing.

AJAX: await instead of callbacks

jQuery passes the server's answer to functions you give it. Nyx gives you the answer with await, so code reads from top to bottom, and errors are caught with try / catch:

jQuery

$.getJSON("/api/students")
  .done(function (students) {
    showList(students);
  })
  .fail(function () {
    alert("Couldn't load");
  });

Nyx

try {
  const students = await nyx.get("/api/students");
  showList(students);
} catch (error) {
  nyx.toast(error.message, "error");
}
Sending to PHP? Add { as: "form" }

$.post() sends data the way an HTML form does, which PHP reads as $_POST. nyx.post() sends JSON, which modern servers prefer, but which $_POST can't see. When converting code that talks to PHP, add { as: "form" }: nyx.post("save.php", data, { as: "form" }). In WordPress, nyx.wp.ajax() does this for you.

Nyx spots jQuery habits

Old habits are hard to break, so Nyx watches for jQuery code and tells you the Nyx way, once each. The old names still do their job, so your page doesn't break while you learn. Run this jQuery-flavoured code and read the Output:

Hello

Nyx also explains the errors jQuery habits cause when jQuery isn't on the page:

JavaScript saysNyx adds
$ is not defined$ is jQuery's name, and jQuery isn't on this page. Write nyx("#menu") instead of $("#menu").
nyx.get(...).done is not a function.done() on a request is jQuery's style. Use await with try / catch.

Converting code, step by step

Here's a typical jQuery snippet from a tutorial, an FAQ where clicking a question shows its answer:

$(document).ready(function () {
  $(".question").click(function () {
    $(this).next(".answer").slideToggle(300);
    $(this).toggleClass("open");
  });
});
  1. Replace the ready wrapper$(document).ready(function () { ... }) becomes nyx(() => { ... }).
  2. Replace $( with nyx($(".question") becomes nyx(".question").
  3. Use .on() and the wrapped element.click(function () { $(this) ... }) becomes .on("click", (event, question) => { question ... }).
  4. Write times in wordsslideToggle(300) becomes slideToggle("300ms").
  5. Run it, and read the consoleNyx tells you about anything it doesn't recognise.

How do I join the library?

Can I borrow e-books?

What Nyx leaves out

Nyx is smaller than jQuery on purpose, so there's less to learn. These parts of jQuery have no Nyx version, because modern JavaScript already does them well:

jQueryUse instead
$.Deferred(), $.when()Promises with await, or Promise.all([...]) to wait for several things.
$.each(), $.map(), $.grep()A list's own .forEach(), .map() and .filter().
.queue(), .dequeue()Nyx chains animations for you: .fadeOut().wait("1 second").fadeIn().
Event names like "click.menu"Keep the function in a variable and remove it with .off("click", fn).
jQuery pluginsThey need jQuery. Keep jQuery for them; Nyx works alongside it.

What Nyx adds

Nyx also has tools jQuery doesn't, for things real websites need every day:

NyxWhat it does
Friendly errorsExplains mistakes, with the file and line. Finding and fixing mistakes
.pick(), .picker(), .markCurrent()The "active" item in menus and tabs. Events
.busy(), { latest }, { retry }Safer requests. Servers and AJAX
nyx.wpWordPress AJAX and REST, with nonces. Using Nyx in WordPress
nyx.after(), nyx.every(), nyx.countdown()Timers in words. Timers and delays
nyx.money(), nyx.date(), nyx.ago(), nyx.plural()Formatting for every country. Formatting
nyx.remember(), nyx.state()Saving data, and state with undo. Saving data and smart state
nyx.check()Form checking with short rules. Checking forms
nyx.search()Search that forgives typos. Searching lists
nyx.toast(), nyx.copy(), nyx.shortcut(), nyx.chart()Everyday helpers. Everyday helpers

jQuery and Nyx on the same page

You don't have to convert everything at once. Nyx never touches $ or jQuery, so both can be loaded on the same page, which is common in WordPress, where many themes and plugins need jQuery. Write new code with Nyx and convert old code when you have time.

<script src="jquery.min.js"></script>
<script src="nyx.js"></script>
<script src="old-slider.js"></script>   <!-- still uses $ -->
<script src="site.js"></script>         <!-- your new Nyx code -->

If something else on the page already uses the name nyx, write const N = nyx.noConflict(); and use N(...) instead.

Exercise

Convert each line of jQuery to Nyx. Fill in the blanks, then press Check answers.

1. $("#menu").hide();

("#menu").hide();

2. const name = $("#name").val();

const name = nyx("#name").();

3. $(".tab").on("click", function () { $(this).addClass("active"); });

nyx(".tab").on("click", (event, ) => { tab.addClass("active"); });

4. $("#note").fadeIn().delay(2000).fadeOut();

nyx("#note").fadeIn().("2 seconds").fadeOut();

5. $("#box").fadeOut(400, showNext);

nyx("#box").fadeOut("400ms").(showNext);

6. $.getJSON("/api/posts", function (posts) { ... });

const posts =  nyx.get("/api/posts");

7. $("li").each(function (i, el) { ... });

nyx("li").each(() => { ... });

Remember

Most jQuery becomes Nyx by writing nyx instead of $. Many method names are the same.
Handlers get the element wrapped: (event, item) instead of $(this).
.each((item, i) => ...): the item comes first, unlike jQuery.
Times are words ("400ms"), and .done() runs code after an animation.
Requests use await and try / catch. Add { as: "form" } when PHP reads $_POST.
Nyx points out jQuery habits, and works next to jQuery on the same page.