typestar

URLs without a reload in JavaScript

pushState changes the address bar; popstate tells you about back.

function navigate(path, { push = true } = {}) {
  if (push) {
    history.pushState({ path }, "", path);
  } else {
    history.replaceState({ path }, "", path);
  }
  render(path);
}

function render(path) {
  const [, lang, tour] = path.split("/");
  document.title = tour ? `${lang} - ${tour}` : lang || "typestar";
  return { lang, tour };
}

window.addEventListener("popstate", (event) => {
  render(event.state?.path ?? location.pathname);
});

How it works

  1. pushState adds an entry, replaceState rewrites the current one.
  2. The popstate handler is where you re-render.
  3. The URL must stay same-origin.

Keywords and builtins used here

The run, in numbers

Lines
18
Characters to type
425
Tokens
133
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 76 seconds.

Type this snippet

Step 1 of 2 in URLs & formatting, step 11 of 13 in The browser.

← Previous Next →