driver.js Documentation

A lightweight, dependency-free JavaScript library for guiding user focus across the page.

RAW Doc

Technical Documentation: kamranahmedse/driver.js

โ„น๏ธ Provenance: Multi-Tier Ingestion ยท CodeWiki Reference

Apps Docs Src Content Guides Api (`apps/docs/src/content/guides/api.mdx`)


title: "API Reference" groupTitle: "Reference" sort: 51

driver() returns an object with the methods below. The options it takes are in Configuration.

js
import { driver } from "driver.js";
import "driver.js/dist/driver.css";

const driverObj = driver({
  steps: [
    { element: "#search", popover: { title: "Search" } },
    { element: "#export", popover: { title: "Export" } },
  ],
});

Starting and Stopping

js
driverObj.drive(); // Start the tour at the first step
driverObj.drive(2); // Start at the third step

// Show one step on its own, without a tour
driverObj.highlight({
  element: "#search",
  popover: { title: "Search", description: "Find anything." },
});

driverObj.destroy(); // End the tour or highlight
driverObj.isActive(); // true while a tour or highlight is showing

destroy() doesn't run onDestroyStarted, so you can call it from that hook. The other destroy hooks get the reason "api", or the reason of the user action when you call it from a hook.

js
driverObj.moveNext(); // Go to the next step. Ends the tour on the last one
driverObj.movePrevious(); // Go to the previous step
driverObj.moveTo(3); // Go to the step with this index
driverObj.advance(); // Complete the current step

advance() completes the step the way advanceOn does: it waits for advanceDelay, then runs onNextClick or moves on. Use it when your app decides the step is done, like after a save. moveNext() moves right away and doesn't run onNextClick.

js
{
  element: "#save",
  advanceDelay: 600,
  onHighlighted: (element, step, { signal, driver }) => {
    window.addEventListener("profile-saved", () => driver.advance(), {
      signal,
    });
  },
  popover: {
    title: "Save your profile",
    instruction: "Click <b>Save</b>.",
  },
}

movePrevious() on the first step and moveTo() with an index that doesn't exist end the tour. moveTo() also starts the tour when it isn't running, like drive(). moveNext() and movePrevious() do nothing then.

The Current Step

js
driverObj.getActiveIndex(); // Active step index, undefined in highlight()
driverObj.getActiveStep(); // The active step
driverObj.getActiveElement(); // The highlighted element

driverObj.getPreviousStep(); // The step that was active before this one
driverObj.getPreviousElement(); // And its element
driverObj.getNextStep(); // The step moveNext() would show

driverObj.isFirstStep(); // No step to go back to
driverObj.isLastStep(); // No step to go on to
driverObj.hasNextStep();
driverObj.hasPreviousStep();

These account for steps that skipMissingElement would skip. isFirstStep() and isLastStep() return false when no tour is running.

Changing the Popover

js
// Change the visible popover. Changes merge, and last until the step
// is left.
driverObj.updatePopover({ description: "Almost there." });
driverObj.updatePopover({
  nextBtnText: "Continue",
  disableButtons: ["previous"],
});

// Restore the step's own popover
driverObj.updatePopover();

updatePopover() takes title, description, instruction, showButtons, disableButtons, showProgress, progressText, nextBtnText, prevBtnText, closeBtnLabel and popoverClass. Changed text is announced to screen readers. It can change the text of an action step, but not turn a step into one.

js
// Shake the popover to draw attention to it
driverObj.nudge();

// Shake it and show a line of feedback under the instruction.
// The line goes away with the next nudge() or step.
driverObj.nudge("Not that one. Click <b>Inbox</b>.");

// Shake it and change the popover like updatePopover() does
driverObj.nudge({ description: "Not quite. Choose Editor." });
js
// Redraw the highlight and popover after a layout change.
// Resizes, scrolling and size changes of the element are followed already.
driverObj.refresh();

Configuration

js
driverObj.getConfig(); // The current configuration
driverObj.getState(); // The current state, see Configuration
driverObj.getState("activeIndex"); // One key of it

// Replace the steps
driverObj.setSteps([
  { element: "#billing", popover: { title: "Billing" } },
]);

// Replace the configuration
driverObj.setConfig({ ...driverObj.getConfig(), showProgress: true });

setConfig() replaces the whole configuration, including steps. Spread getConfig() to keep what you had. After setSteps() on a running tour, call drive() to show the new steps.

Types

ts
import type {
  Config,
  DriveStep,
  Popover,
  Driver,
  State,
  PopoverDOM,
  PopoverPatch,
  DriverHook,
  HookOpts,
  DestroyReason,
  AdvanceOn,
  AdvanceOnEvent,
  AllowedElements,
  InteractionHook,
  ElementMissing,
  ElementMissingHook,
  Side,
  Alignment,
  AllowedButtons,
} from "driver.js";

Hints

hints() returns its own object. Options are in Hints Configuration, examples in the Hints guide.

js
import { hints } from "driver.js/hints";
import "driver.js/dist/hints.css";

const productHints = hints({
  hints: [
    { element: "#export", id: "export", popover: { title: "Export" } },
  ],
});

// Show the beacons. Call again to pick up elements that appeared since
productHints.show();
productHints.hide(); // Remove the beacons
productHints.isVisible();

// By id, or by index when the hint has no id
productHints.open("export"); // Open a hint's popover
productHints.close(); // Close the open popover, keeping its beacon
productHints.dismiss("export"); // Remove a hint's beacon and run onDismiss
productHints.restore("export"); // Bring a dismissed hint back
productHints.restoreAll();

productHints.getHints(); // The configured hints
productHints.getActive(); // The hint whose popover is open, if any
productHints.setHints([]); // Replace the hints. Dismissals are forgotten

productHints.refresh(); // Reposition after a layout change

Checklists

checklist() returns its own object. Options are in Checklist Configuration, examples in the Checklists guide.

js
import { checklist } from "driver.js/checklist";
import "driver.js/dist/driver.css";
import "driver.js/dist/checklist.css";

const onboarding = checklist({
  id: "onboarding",
  items: [
    {
      id: "tour",
      title: "Take the tour",
      tour: [{ element: "#search", popover: { title: "Search" } }],
    },
    { id: "github", title: "Connect GitHub" },
  ],
});

onboarding.show(); // Add the widget to the page
onboarding.hide(); // Remove it
onboarding.isVisible();

onboarding.open(); // Open the panel
onboarding.close(); // Close the panel, keeping the launcher
onboarding.toggle();
onboarding.isOpen();

onboarding.start("tour"); // Run an item's tour, link or action
onboarding.complete("github"); // Tick an item
onboarding.uncomplete("github"); // Untick it
onboarding.reset(); // Untick every item
onboarding.refresh(); // Check every item's completeWhen again

onboarding.getProgress(); // { completed: ["github"], done: 1, total: 2 }
onboarding.getItems(); // The configured items

Apps Docs Src Content Guides Custom Buttons (`apps/docs/src/content/guides/custom-buttons.mdx`)


title: "Custom Buttons" groupTitle: "Recipes" sort: 45 sidebar: false

import { RecipeSample } from "../../components/RecipeSample.tsx";
import { TranslateDemo } from "../../components/RecipeDemos.tsx";

Use this when Next, Previous and Done aren't enough: a way to skip the tour from any step, a restart at the end, or button text in the user's language.

Skip and Restart

onPopoverRender gets the popover's DOM before it shows, so you can add your own buttons. The driver-popover-footer-btn class gives them the default button look.

```js const driverObj = driver({ showButtons: ["next", "previous"], steps: [ // ... ], onPopoverRender: (popover, { driver }) => { const button = document.createElement("button"); button.className = "driver-popover-footer-btn";
text
if (driver.isLastStep()) {
    button.innerText = "Restart";
    button.addEventListener("click", () => driver.drive(0));
  } else {
    button.innerText = "Skip tour";
    button.addEventListener("click", () => driver.destroy());
  }

  popover.footerButtons.prepend(button);
},

});

driverObj.drive();

text
</RecipeSample>

The parts of the popover you can reach are listed in [Theming](/docs/theming#changing-the-popover-dom).

## Rename and Translate

The built-in buttons take their text from options, and HTML is allowed. Pick the strings for the user's language. Switch the language below and run the tour.


```js
const labels = {
  en: {
    next: "Next",
    prev: "Back",
    done: "Done",
    of: "of",
    close: "Close tour",
  },
  de: {
    next: "Weiter",
    prev: "Zurรผck",
    done: "Fertig",
    of: "von",
    close: "Tour schlieรŸen",
  },
};

const lang = navigator.language.slice(0, 2);
const t = labels[lang] ?? labels.en;

const driverObj = driver({
  showProgress: true,
  nextBtnText: `${t.next} &rarr;`,
  prevBtnText: `&larr; ${t.prev}`,
  doneBtnText: t.done,
  progressText: `{{current}} ${t.of} {{total}}`,
  closeBtnLabel: t.close,
  steps: [
    // ...
  ],
});

Set them on a step's popover to change one step only, like "Let's go" on the first.

Uses: onPopoverRender, button text, progressText, API


Apps Docs Src Content Guides First Run Onboarding (`apps/docs/src/content/guides/first-run-onboarding.mdx`)


title: "First-Run Onboarding" groupTitle: "Recipes" sort: 30

import { RecipeSample } from "../../components/RecipeSample.tsx";

Use this for the welcome tour new users should see once. The tour starts on the first visit, never comes back on its own, and a button replays it on demand.

Load the page below, close or finish the tour, then load it again.

```js import { driver } from "driver.js"; import "driver.js/dist/driver.css";

const SEEN_KEY = "onboarding-seen";

const tour = driver({
showProgress: true,
steps: [
{ element: "#projects", popover: { title: "Projects" } },
{ element: "#invite", popover: { title: "Invite" } },
{ element: "#replay-tour", popover: { title: "Replay" } },
],
onDestroyed: () => localStorage.setItem(SEEN_KEY, "1"),
});

if (!localStorage.getItem(SEEN_KEY)) {
tour.drive();
}

document
.querySelector("#replay-tour")
.addEventListener("click", () => tour.drive());

text
</RecipeSample>

- `onDestroyed` runs however the tour ends, so closing it early counts as seen too. To show it again until it's finished, save only when `reason` is `"done"` (see [Track Tour Analytics](/docs/track-tour-analytics)).
- For signed-in users, save the flag on the user record instead, so it follows them to other devices.
- Start the tour once the page has rendered. In React or Vue, see [React and Vue](/docs/react-and-vue).

**Uses**: [`drive()`](/docs/api#starting-and-stopping), [`onDestroyed`](/docs/configuration#hooks), [`showProgress`](/docs/tour-basics#tour-progress)

---

### Apps Docs Src Content Guides Installation (`apps/docs/src/content/guides/installation.mdx`)

---
title: "Installation"
groupTitle: "Introduction"
sort: 1
---

Install the package:

```bash
npm install driver.js
# or
pnpm add driver.js
# or
yarn add driver.js

Import the library and its stylesheet, then highlight an element:

js
import { driver } from "driver.js";
import "driver.js/dist/driver.css";

const driverObj = driver();

driverObj.highlight({
  element: "#some-element",
  popover: {
    title: "Title",
    description: "Description",
  },
});

Hints and Checklists

Hints and checklists are separate entries, so you only load them when you use them.

js
import { hints } from "driver.js/hints";
import "driver.js/dist/hints.css";
js
import { checklist } from "driver.js/checklist";
import "driver.js/dist/driver.css";
import "driver.js/dist/checklist.css";

Hints don't need driver.css. Checklists do, because their items run tours.

Headless tours draw nothing, so they need no stylesheet.

js
import { driver } from "driver.js/headless";

CDN

html
<script
  src="https://cdn.jsdelivr.net/npm/driver.js@latest/dist/driver.js.iife.js"
></script>
<link
  rel="stylesheet"
  href="https://cdn.jsdelivr.net/npm/driver.js@latest/dist/driver.css"
/>


<script
  src="https://cdn.jsdelivr.net/npm/driver.js@latest/dist/hints.iife.js"
></script>
<link
  rel="stylesheet"
  href="https://cdn.jsdelivr.net/npm/driver.js@latest/dist/hints.css"
/>


<script
  src="https://cdn.jsdelivr.net/npm/driver.js@latest/dist/checklist.iife.js"
></script>
<link
  rel="stylesheet"
  href="https://cdn.jsdelivr.net/npm/driver.js@latest/dist/checklist.css"
/>


<script
  src="https://cdn.jsdelivr.net/npm/driver.js@latest/dist/headless.iife.js"
></script>

The CDN builds expose globals instead of modules:

js
const driver = window.driver.js.driver;
const hints = window.driverHints.hints;
const checklist = window.driverChecklist.checklist;
const headless = window.driverHeadless.driver;

const driverObj = driver();

Next: Basic Usage.


Apps Docs Src Content Guides Popover (`apps/docs/src/content/guides/popover.mdx`)


title: "Popover" groupTitle: "Tours" sort: 11

import { CodeSample } from "../../components/CodeSample.tsx";

Every step and highlight can show a popover next to its element. This page covers where it sits and which buttons it has. To change how it looks, see Theming.

Position

side picks the side of the element the popover sits on: "top", "right", "bottom" (default) or "left". align places it along that side: "start" (default), "center" or "end".

js
import { driver } from "driver.js";
import "driver.js/dist/driver.css";

const driverObj = driver();

driverObj.highlight({
  element: "#sample-box",
  popover: {
    title: "Left Start",
    description: "On the left, aligned with the top edge.",
    side: "left",
    align: "start",
  },
});

Use the buttons below to show the popover.

<CodeSample
buttonText={"Left Start"}
highlight={{
element: "#sample-box",
popover: {
title: "Left Start",
side: "left",
align: "start",
},
}}
id={"left-start"}
client:load
/>
<CodeSample
buttonText={"Left Center"}
highlight={{
element: "#sample-box",
popover: {
title: "Left Center",
side: "left",
align: "center",
},
}}
id={"left-center"}
client:load
/>
<CodeSample
buttonText={"Left End"}
highlight={{
element: "#sample-box",
popover: {
title: "Left End",
side: "left",
align: "end",
},
}}
id={"left-end"}
client:load
/>
<CodeSample
buttonText={"Top Start"}
highlight={{
element: "#sample-box",
popover: {
title: "Top Start",
side: "top",
align: "start",
},
}}
id={"top-start"}
client:load
/>
<CodeSample
buttonText={"Top Center"}
highlight={{
element: "#sample-box",
popover: {
title: "Top Center",
side: "top",
align: "center",
},
}}
id={"top-center"}
client:load
/>
<CodeSample
buttonText={"Top End"}
highlight={{
element: "#sample-box",
popover: {
title: "Top End",
side: "top",
align: "end",
},
}}
id={"top-end"}
client:load
/>
<CodeSample
buttonText={"Right Start"}
highlight={{
element: "#sample-box",
popover: {
title: "Right Start",
side: "right",
align: "start",
},
}}
id={"right-start"}
client:load
/>
<CodeSample
buttonText={"Right Center"}
highlight={{
element: "#sample-box",
popover: {
title: "Right Center",
side: "right",
align: "center",
},
}}
id={"right-center"}
client:load
/>
<CodeSample
buttonText={"Right End"}
highlight={{
element: "#sample-box",
popover: {
title: "Right End",
side: "right",
align: "end",
},
}}
id={"right-end"}
client:load
/>
<CodeSample
buttonText={"Bottom Start"}
highlight={{
element: "#sample-box",
popover: {
title: "Bottom Start",
side: "bottom",
align: "start",
},
}}
id={"bottom-start"}
client:load
/>
<CodeSample
buttonText={"Bottom Center"}
highlight={{
element: "#sample-box",
popover: {
title: "Bottom Center",
side: "bottom",
align: "center",
},
}}
id={"bottom-center"}
client:load
/>
<CodeSample
buttonText={"Bottom End"}
highlight={{
element: "#sample-box",
popover: {
title: "Bottom End",
side: "bottom",
align: "end",
},
}}
id={"bottom-end"}
client:load
/>

When the popover doesn't fit on that side, it moves to one where it does. Scroll the box near an edge of the window and try again.

Buttons

showButtons picks the buttons: "next", "previous" and "close". A tour shows all three by default. Set it on the driver for every step, or on a step's popover.

<CodeSample
buttonText={"Next and Previous Only"}
config={{
showButtons: ['next', 'previous'],
}}
tour={[
{ element: '.line:nth-child(5)', popover: { title: 'No Close Button', description: 'Escape and a click on the overlay still close the tour.', side: "bottom", align: 'start' } },
{ element: '.line:nth-child(12)', popover: { title: 'Last Step', description: 'Next reads Done here.', side: "top", align: 'start' } },
]}
id={"buttons-sample"}
client:load>
```js
import { driver } from "driver.js";
import "driver.js/dist/driver.css";

text
const driverObj = driver({
  showButtons: ["next", "previous"],
  steps: [
    { element: "#search", popover: { title: "Search" } },
    { element: "#export", popover: { title: "Export" } },
  ],
});

driverObj.drive();
```
  • disableButtons takes the same values and shows the button greyed out. Previous is disabled on the first step.
  • The arrow keys follow the buttons: they do nothing when their button is hidden or disabled. Escape does nothing when the close button is disabled.
  • highlight() shows no buttons by default. Outside a tour, Next and Previous only do something if you set onNextClick and onPrevClick.
  • A step with popover.instruction keeps the Next button but shows it disabled until the user has done it.

Change Button Text

nextBtnText, prevBtnText and doneBtnText set the button text, and HTML is allowed. closeBtnLabel sets the screen reader label of the close button.

<CodeSample
config={{
showProgress: true,
nextBtnText: 'Next →',
prevBtnText: '← Back',
doneBtnText: 'Finish',
closeBtnLabel: 'Close tour',
}}
tour={[
{ element: '.line:nth-child(5)', popover: { title: 'Next', description: 'With an arrow.', side: "bottom", align: 'start' } },
{ element: '.line:nth-child(7)', popover: { title: 'Done', description: 'The last step uses doneBtnText.', side: "bottom", align: 'start' } },
]}
id={"button-text"}
client:load>

js
import { driver } from "driver.js";
import "driver.js/dist/driver.css";

const driverObj = driver({
  nextBtnText: "Next &rarr;",
  prevBtnText: "&larr; Back",
  doneBtnText: "Finish",
  closeBtnLabel: "Close tour",
  steps: [
    // ...
  ],
});

driverObj.drive();

Event Handlers

onNextClick, onPrevClick, onCloseClick and onDoneClick run instead of the button's default action. The tour then only moves or ends when you call moveNext(), movePrevious() or destroy(). Set them on the driver for every step, or on a step's popover.

onDoneClick runs on the last step instead of onNextClick, so it tells you the user finished the tour.

<CodeSample
buttonText={"Show Example"}
config={{}}
tour={[
{ element: '.line:nth-child(8)', popover: { title: 'Open Your Console', description: 'Each button logs a line before doing its job.', side: "bottom", align: 'start' } },
{ element: '.line:nth-child(20)', popover: { title: 'Last Step', description: 'Done runs onDoneClick, not onNextClick.', side: "bottom", align: 'start' } },
]}
id={"logger-events"}
client:load>

js
import { driver } from "driver.js";
import "driver.js/dist/driver.css";

const driverObj = driver({
  steps: [
    // ...
  ],
  onNextClick: () => {
    console.log("Next clicked");
    driverObj.moveNext();
  },
  onPrevClick: () => {
    console.log("Previous clicked");
    driverObj.movePrevious();
  },
  onCloseClick: () => {
    console.log("Close clicked");
    driverObj.destroy();
  },
  onDoneClick: () => {
    console.log("Done clicked");
    driverObj.destroy();
  },
});

driverObj.drive();

onNextClick also runs when the step is completed another way: the right arrow key, an overlay click with overlayClickBehavior: "nextStep", advanceOn or advance(). For loading something before the next step, see Wait for a Save.

To add your own buttons, like Skip or Restart, or translate the built-in ones, see Custom Buttons.


Apps Docs Src Content Guides Start From A Help Menu (`apps/docs/src/content/guides/start-from-a-help-menu.mdx`)


title: "Start From a Help Menu" groupTitle: "Recipes" sort: 41 sidebar: false

import { RecipeSample } from "../../components/RecipeSample.tsx";

Use this for a tour people come back to. "Take the tour" in your help menu starts at the part that explains the screen they're on, not at step one.

Pick a screen below, then take the tour.

```js const steps = [ { element: "#tab-inbox", data: { screen: "inbox" }, popover: { title: "Inbox" }, }, { element: "#tab-reports", data: { screen: "reports" }, popover: { title: "Reports" }, }, { element: "#tab-settings", data: { screen: "settings" }, popover: { title: "Settings" }, }, ];

const driverObj = driver({
showProgress: true,
steps,
onHighlighted: (element, step) => {
showScreen(step.data.screen);
},
});

document
.querySelector("#help-take-tour")
.addEventListener("click", () => {
const index = steps.findIndex(
step => step.data.screen === currentScreen()
);
driverObj.drive(Math.max(index, 0));
});

text
</RecipeSample>

- A step's `data` holds anything you want to keep with it, here the screen it belongs to.
- `drive(index)` starts at that step. Previous still goes back to the earlier ones.
- If the tour is already running, `driverObj.moveTo(index)` jumps to a step without starting over.

**Uses**: [`drive(index)` and `moveTo()`](/docs/api#navigation), [step `data`](/docs/configuration#step-configuration), [`onHighlighted`](/docs/configuration#hooks)

---

### Apps Docs Src Content Guides Steps Inside A Dialog (`apps/docs/src/content/guides/steps-inside-a-dialog.mdx`)

---
title: "Steps Inside a Dialog"
groupTitle: "Recipes"
sort: 33
---

import { InteractiveSample } from "../../components/InteractiveSample.tsx";

Use this when the task happens in a modal, like creating a project or confirming a payment. The tour opens the dialog with the user, works inside it, and comes back to the page when it closes.


```js
const driverObj = driver({
  showButtons: ["close"],
  steps: [
    {
      element: "#new-project",
      advanceOn: "click",
      popover: {
        title: "Start a project",
        instruction: "Click <b>New project</b>.",
      },
    },
    {
      element: "dialog #project-name",
      waitForElement: 1000,
      popover: {
        title: "Name it",
        showButtons: ["next", "close"],
        side: "top",
      },
    },
    {
      element: "dialog #create",
      advanceOn: "click",
      popover: {
        title: "Create it",
        instruction: "Click <b>Create</b>.",
      },
    },
    {
      element: "#created",
      waitForElement: 1000,
      popover: { title: "Created", showButtons: ["next"] },
    },
  ],
});

driverObj.drive();
  • The overlay and the popover render inside the dialog, including one opened with showModal(), so the rest of the dialog is dimmed like the page and the popover shows above it.
  • waitForElement on the first step inside covers the time the dialog takes to open.
  • allowedElements inside the dialog get their own cutout in the overlay.
  • When the dialog closes mid-step, the overlay and the popover move back to the page.

Uses: waitForElement, advanceOn, popover.instruction


--- METRICS ---