# Installation
> Install Driver.js with npm, yarn, pnpm, or a CDN script tag and add the lightweight, zero-dependency JavaScript tour library to your project in seconds.
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](https://driverjs.com/docs/hints.md) and [checklists](https://driverjs.com/docs/checklists.md) 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](https://driverjs.com/docs/headless-tours.md) draw nothing, so they need no stylesheet.
```js
import { driver } from "driver.js/headless";
```
## CDN
```html
```
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](https://driverjs.com/docs/basic-usage.md).
---
# Basic Usage
> Get started with Driver.js: import the library, configure your steps, and create your first multi-step product tour or element highlight in minutes.
Driver.js does three things: tours, single highlights and hints. Each starts with a few lines.
## A Tour
Pass `steps` to `driver()` and call `drive()`. Each step points at an element and describes it in a popover.
```js
import { driver } from "driver.js";
import "driver.js/dist/driver.css";
const driverObj = driver({
showProgress: true,
steps: [
{
element: ".page-header",
popover: {
title: "Header",
description: "Search and account live here.",
},
},
{
element: ".sidebar",
popover: { title: "Sidebar" },
},
{ popover: { title: "That's it" } },
],
});
driverObj.drive();
```
More in [Tour Basics](https://driverjs.com/docs/tour-basics.md). To make steps wait for the user, see [Interactive Tours](https://driverjs.com/docs/interactive-tours.md) and [Action-Driven Tours](https://driverjs.com/docs/action-driven-tours.md).
## A Single Highlight
`highlight()` takes one step and shows it on its own, without navigation buttons.
```js
import { driver } from "driver.js";
import "driver.js/dist/driver.css";
const driverObj = driver();
driverObj.highlight({
element: "#some-element",
popover: {
title: "Title for the Popover",
description: "Description for it",
},
});
```
More in [Simple Highlight](https://driverjs.com/docs/simple-highlight.md).
## Hints
Hints are pulsing beacons that open a popover when clicked. There is no overlay and the page stays usable. They come from their own entry.
```js
import { hints } from "driver.js/hints";
import "driver.js/dist/hints.css";
const productHints = hints({
hints: [
{
element: "#export-btn",
popover: {
title: "Export your data",
description: "Download this report as CSV or PDF.",
},
},
{
element: "#summary",
popover: {
title: "Auto-generated summary",
description: "Written for you from the numbers.",
},
},
],
});
productHints.show();
```
More in the [Hints guide](https://driverjs.com/docs/hints.md). For onboarding task lists, see [Checklists](https://driverjs.com/docs/checklists.md).
Driver.js needs no wrapper for React, Vue or Next.js. See [React and Vue](https://driverjs.com/docs/react-and-vue.md) for the setup and cleanup.
Next: every option is in [Configuration](https://driverjs.com/docs/configuration.md), every method in the [API Reference](https://driverjs.com/docs/api.md). For ready-made solutions to common jobs, like first-run onboarding or a tour that resumes, see [All Recipes](https://driverjs.com/docs/recipes.md).
---
# Tour Basics
> Build a multi-step product tour with Driver.js. Animate between steps or jump instantly, tune the animation speed, and show a step counter like 1 of 5.
A tour is a list of steps. Each step highlights an element and describes it in a popover. Pass the steps to `driver()` and call `drive()`.
## Animated Tour
The highlight glides from one step to the next by default. Users move with the buttons or the arrow keys, and close with Escape .
```js
import { driver } from "driver.js";
import "driver.js/dist/driver.css";
const driverObj = driver({
showProgress: true,
steps: [
{
element: ".page-header",
popover: {
title: "Header",
description: "Search lives here.",
side: "bottom",
},
},
{
element: ".sidebar",
popover: { title: "Sidebar", side: "right" },
},
{ popover: { title: "Happy Coding" } },
],
});
driverObj.drive();
```
### Animation Duration
`duration` sets how long the move between steps and the fade-in take, in milliseconds. The default is `400`.
```js
import { driver } from "driver.js";
import "driver.js/dist/driver.css";
const driverObj = driver({
duration: 150,
steps: [
// ...
],
});
driverObj.drive();
```
## Static Tour
`animate: false` turns the animation off. The highlight jumps straight to each step.
```js
import { driver } from "driver.js";
import "driver.js/dist/driver.css";
const driverObj = driver({
animate: false,
steps: [
// ...
],
});
driverObj.drive();
```
## Tour Progress
`showProgress: true` shows the step count in the popover's bottom left corner, as `{{current}} of {{total}}`. Change the text with `progressText`.
```js
import { driver } from "driver.js";
import "driver.js/dist/driver.css";
const driverObj = driver({
showProgress: true,
progressText: "Step {{current}} of {{total}}",
steps: [
// ...
],
});
driverObj.drive();
```
Both can be set per step in its `popover` as well.
---
# Popover
> Position Driver.js popovers with the side and align options, choose which buttons they show, change the button text, and add your own buttons and click handlers.
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](https://driverjs.com/docs/theming.md).
## 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",
},
});
```
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`.
```js
import { driver } from "driver.js";
import "driver.js/dist/driver.css";
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`](https://driverjs.com/docs/action-driven-tours.md#make-the-user-act) 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.
```js
import { driver } from "driver.js";
import "driver.js/dist/driver.css";
const driverObj = driver({
nextBtnText: "Next →",
prevBtnText: "← 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.
```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`](https://driverjs.com/docs/interactive-tours.md#advance-on-click) or `advance()`. For loading something before the next step, see [Wait for a Save](https://driverjs.com/docs/wait-for-a-save.md#when-next-does-the-work).
To add your own buttons, like Skip or Restart, or translate the built-in ones, see [Custom Buttons](https://driverjs.com/docs/custom-buttons.md).
---
# Simple Highlight
> Highlight any element on the page with Driver.js. Spotlight a single element and show a popover to deliver contextual help, beyond just product tours.
`highlight()` shows a single step without a tour. Use it for contextual help: explain a feature, guide a form, or dim the page around one element.
```js
import { driver } from "driver.js";
import "driver.js/dist/driver.css";
const driverObj = driver({
popoverClass: "driverjs-theme",
stagePadding: 4,
});
driverObj.highlight({
element: "#highlight-me",
popover: {
side: "bottom",
title: "This is a title",
description: "This is a description",
},
});
```
A highlight popover has no buttons unless you ask for them with `showButtons`. The user closes it with Escape or a click on the overlay, and your code closes it with `destroy()`. Leave out `popover` to only dim the page around the element.
## Without an Element
Leave out `element` and the popover shows in the middle of the screen, like a modal. The title and description take HTML.
```js
driverObj.highlight({
popover: {
description:
" " +
"
Yet another highlight example.
",
},
});
```
To show help as the user moves through a form, see [Teach a Form](https://driverjs.com/docs/teach-a-form.md).
For help that sits on the page until the user asks for it, use [hints](https://driverjs.com/docs/hints.md).
---
# Interactive Tours
> Build Driver.js tours that react to your app: advance when users click the highlighted element, wait for elements that render on demand, skip optional steps and follow re-rendered elements.
A tour can follow what happens in your app instead of the Next button. This page covers tours that advance on a click, wait for elements, skip optional steps and survive re-renders.
For tours where every step waits for a specific action and wrong actions get feedback, see [Action-Driven Tours](https://driverjs.com/docs/action-driven-tours.md).
## Advance on Click
`advanceOn: "click"` moves the tour on when the highlighted element is clicked, as if Next was pressed. The element's own click handler still runs. Set it for the whole tour or per step.
```js
import { driver } from "driver.js";
import "driver.js/dist/driver.css";
const driverObj = driver({
advanceOn: "click",
showProgress: true,
steps: [
{ element: "#plan", popover: { title: "Pick a Plan" } },
{ element: "#billing", popover: { title: "Billing" } },
{ element: "#checkout", popover: { title: "Checkout" } },
],
});
driverObj.drive();
```
`advanceOn` takes any event, like `"change"` or `"dblclick"`. To remove the Next button so the click is the only way forward, make the step an [action step](https://driverjs.com/docs/action-driven-tours.md#make-the-user-act). `advanceOnClick: true` from earlier versions still works but is deprecated.
## Wait for Elements
A click often leads to something that doesn't exist yet, like a modal. Give the next step a `waitForElement` time in milliseconds: the tour stays on the current step, with its popover in a waiting state, until the element appears. Below, Next renders the element about a second later.
```js
import { driver } from "driver.js";
import "driver.js/dist/driver.css";
const driverObj = driver({
steps: [
{
element: "#open-modal",
advanceOn: "click",
popover: { title: "Open", instruction: "Click Open ." },
},
{
element: "#modal-confirm",
waitForElement: 5000,
popover: { title: "Confirm", description: "Now it's here." },
},
],
});
driverObj.drive();
```
If the element never appears, the step shows without it, centered on the screen. To keep the user on the current step instead, set [`onElementMissing`](https://driverjs.com/docs/action-driven-tours.md#recover-from-a-slow-load).
## Optional Steps
Some elements only exist for some users. With `skipMissingElement: true`, a step whose element is not on the page is skipped, forwards and backwards. Run the tour below with and without the banner.
```js
const driverObj = driver({
steps: [
{
element: "#stats",
popover: {
title: "Your numbers",
description: "Updated every hour.",
},
},
{
element: "#trial-banner",
skipMissingElement: true,
popover: {
title: "Trial banner",
description: "Only trial accounts see this step.",
},
},
{
element: "#export",
popover: {
title: "Export",
description: "Download the numbers as CSV.",
},
},
],
});
driverObj.drive();
```
Set it on the driver to apply it to every step. Steps without an `element` are never skipped. Combined with `waitForElement`, the step is skipped only after the wait runs out.
## Elements That Re-render
Frameworks often replace an element instead of updating it. When the highlighted element is replaced, the step moves to the new element that matches its selector. There is nothing to configure. A step that got an element object instead of a selector or function has nothing to look up, so prefer selectors.
```js
const driverObj = driver({
steps: [
{
element: "#sync-row",
popover: {
title: "Sync status",
description: "Click Sync now a few times.",
},
},
],
});
driverObj.drive();
```
When the element is removed and nothing replaces it, [`onElementMissing`](https://driverjs.com/docs/configuration.md#missing-elements) decides what happens.
## More Recipes
- [Steps Inside a Dialog](https://driverjs.com/docs/steps-inside-a-dialog.md): point steps at elements in an open ``.
- [Wait for a Save](https://driverjs.com/docs/wait-for-a-save.md): wait for your app between steps, or load something before one.
- [Multi-Page Tours](https://driverjs.com/docs/multi-page-tours.md): continue a tour on another page.
---
# Action-Driven Tours
> Build Driver.js tours that only move on when the user performs the real action: type a value, pick an option, click, right-click. Block clicks elsewhere, give feedback on wrong actions and recover when the UI changes.
An action-driven tour waits for the user to do each step: type the email, pick the role, open the menu. There is no Next button to skip it, and a wrong action gets a hint.
The tour below walks through inviting a teammate. Try doing the wrong thing too: click elsewhere, or pick the wrong role.
```js
import { driver } from "driver.js";
import "driver.js/dist/driver.css";
const driverObj = driver({
showButtons: ["next", "close"],
steps: [
{
element: "#invite-email",
advanceOn: {
event: "keydown",
when: (element, step, { event, driver }) => {
if (event.key !== "Enter") {
return false;
}
if (element.value && element.checkValidity()) {
return true;
}
driver.nudge("That doesn't look like an email address yet.");
return false;
},
},
popover: {
title: "Who are you inviting?",
instruction: "Type an email and press Enter .",
},
},
{
element: "#invite-role",
advanceOn: {
event: "change",
when: (element, step, { driver }) => {
if (element.value === "editor") {
return true;
}
driver.nudge("Only editors can edit. Choose Editor .");
return false;
},
},
popover: {
title: "Pick a role",
instruction: "Choose Editor .",
},
},
{
element: "#invite-send",
advanceOn: "click",
popover: {
title: "Send it",
instruction: "Click Send invite .",
},
},
{
element: "#invite-sent",
waitForElement: 3000,
popover: { title: "Invite sent", showButtons: ["next"] },
},
],
});
driverObj.drive();
```
## What You Can Build
| You want to... | Use |
| --- | --- |
| [Move on when the user does something](#move-on-when-something-happens) | `advanceOn: "change"` |
| [Make the user act, not press Next](#make-the-user-act) | `popover.instruction` |
| [Accept only the right gesture](#accept-only-the-right-gesture) | `advanceOn: { event, strict: true }` |
| [Show success before moving on](#show-success-before-moving-on) | `advanceDelay` |
| [Move on only when it's done right](#only-move-on-when-its-right) | `advanceOn: { event, when }` |
| [Move on when your app finishes something](https://driverjs.com/docs/wait-for-a-save.md) | `onHighlighted` + `advance()` |
| [Say what was wrong about a click](#give-a-specific-hint) | `onInteraction` + `nudge()` |
| [Let the user hover an element but not click it](#let-the-user-hover-not-click) | `disableActiveInteraction: "clicks"` |
| [Let the user use a menu the step opens](#let-the-user-use-a-menu) | `allowedElements` |
| [Go back when the element disappears](#let-the-user-use-a-menu) | `onElementMissing: "previousAction"` |
| [Retry after a slow load](#recover-from-a-slow-load) | `onElementMissing` function |
The reference for each option is in [Configuration](https://driverjs.com/docs/configuration.md#interaction).
Recipes that teach a whole task this way:
- [Teach a Form](https://driverjs.com/docs/teach-a-form.md): steps that move on once a field is valid
- [Walk Through a Menu](https://driverjs.com/docs/walk-through-a-menu.md): open a dropdown and pick an item
- [Steps Inside a Dialog](https://driverjs.com/docs/steps-inside-a-dialog.md): a task that happens in a modal
- [Wait for a Save](https://driverjs.com/docs/wait-for-a-save.md): move on when your app is done
- [Right-Click and Double-Click Steps](https://driverjs.com/docs/right-click-and-double-click.md): teach a gesture
## Move On When Something Happens
`advanceOn` takes an event name. The step completes when that event happens on the highlighted element, as if Next was pressed. Your own handlers run first.
```js
const driverObj = driver({
showButtons: ["close"],
steps: [
{
element: "#notifications",
advanceOn: "change",
popover: {
title: "Turn on notifications",
description: "Flip the switch.",
},
},
{
element: "#notifications",
popover: { title: "Notifications on", showButtons: ["next"] },
},
],
});
driverObj.drive();
```
Any DOM event works: `"click"`, `"input"`, `"change"`, `"dblclick"`, `"contextmenu"`. Pass a list to accept any of them: `advanceOn: ["dblclick", "contextmenu"]`. Set it on the driver to apply it to every step.
## Make the User Act
A step with only `advanceOn` still has a Next button. Put the instruction in `popover.instruction` and the step becomes an action step: the instruction gets its own row with a pulsing dot at its end, the Next button looks disabled, and the step only moves on when the user does it. Try clicking Calendar, or the dimmed page.
```js
const driverObj = driver({
steps: [
{
element: "#toolbar",
popover: {
title: "The toolbar",
description: "Everything you use daily is one click away.",
},
},
{
element: "#inbox",
advanceOn: "click",
popover: {
title: "Open your inbox",
description: "New messages land here first.",
instruction: "Click Inbox on the toolbar to open it.",
},
},
{
element: "#inbox-panel",
waitForElement: 1000,
popover: {
title: "Your inbox",
description: "The tour moved on as soon as you clicked.",
},
},
],
});
driverObj.drive();
```
On an action step:
- Next stays where it is but looks disabled. Pressing it, the right arrow key or the dimmed page shakes the popover and points at the instruction instead of moving on or closing the tour. `onNextClick` doesn't run for those presses.
- Previous, the close button and Escape work as usual.
- Without `"next"` in `showButtons` there is no disabled button, only the row and its dot. See [Theming](https://driverjs.com/docs/theming.md#action-steps) to restyle both.
- It completes through `advanceOn`, `driverObj.advance()` or `driverObj.moveNext()`.
### Accept Only the Right Gesture
On an action step the highlighted element stays fully usable: on a double-click step, a right-click still opens your app's context menu. Add `strict: true` and the element takes only the gesture the step waits for. Anything else is blocked and shakes the popover. Right-click the file below.
```js
const driverObj = driver({
showButtons: ["close"],
steps: [
{
element: "#file",
advanceOn: { event: "dblclick", strict: true },
popover: {
title: "Open the file",
instruction: "Double-click report.pdf .",
},
},
{
element: "#opened",
waitForElement: 1000,
popover: { title: "Opened", showButtons: ["next"] },
},
],
});
driverObj.drive();
```
`strict` only applies when every event in `advanceOn` is a click, double-click, right-click or pointer press. With `"input"` or `"change"` it blocks nothing, so the user can still click a field to type in it.
### Show Success Before Moving On
With `advanceDelay`, a completed step pauses before moving on. On an action step the instruction row turns green for the pause, its dot becomes a check mark, and Next turns green too. Click Star below.
```js
const driverObj = driver({
showButtons: ["next", "close"],
steps: [
{
element: "#star",
advanceOn: "click",
advanceDelay: 1200,
popover: {
title: "Star the project",
instruction: "Click Star .",
},
},
{
element: "#starred",
waitForElement: 1000,
popover: { title: "Starred", showButtons: ["next"] },
},
],
});
driverObj.drive();
```
Repeated clicks during the pause are ignored, and leaving the step cancels it. `moveNext()` doesn't pause. To restyle the done state, see [Theming](https://driverjs.com/docs/theming.md#action-steps).
### Going Back After an Action
Previous takes the user back to an action they already did, while the page stays as it is now. Where that would confuse, hide Previous on the step after the action:
```js
{
element: "#inbox-panel",
popover: { title: "Your inbox", showButtons: ["next", "close"] },
}
```
## Only Move On When It's Right
An event says something happened, not that it was right. `when` checks the result: it runs after your app has handled the event, and the step completes only when it returns `true`. Pick Team first.
```js
const driverObj = driver({
showButtons: ["close"],
steps: [
{
element: "#plan",
advanceOn: {
event: "change",
when: (element, step, { driver }) => {
if (element.querySelector("input:checked").value === "pro") {
return true;
}
driver.nudge({
description: "That plan has no reports. Pick Pro .",
});
return false;
},
},
popover: {
title: "Pick a plan",
description: "Choose Pro to get reports.",
},
},
{
element: "#plan",
popover: { title: "Pro it is", showButtons: ["next"] },
},
],
});
driverObj.drive();
```
`when` gets the highlighted element, the step and `{ event, driver, ... }`, so it can check a field's value, which key was pressed or what the app shows now.
When a click starts something that takes time, like a save, call `driverObj.advance()` once your app is done. See [Wait for a Save](https://driverjs.com/docs/wait-for-a-save.md).
## Give a Specific Hint
`onInteraction` sees every click, right-click and double-click during a step, before your app does. `region` says where it happened: `"element"`, `"allowed"` or `"outside"`. Return `false` to block it. `nudge("...")` shakes the popover and shows a line of feedback, which goes away with the next nudge or step. Right-click the file.
```js
const driverObj = driver({
showButtons: ["close"],
onInteraction: (element, step, { event, region, driver }) => {
if (region === "element" && event.type === "contextmenu") {
driver.nudge("That was a right-click. Double-click instead.");
return false;
}
},
steps: [
{
element: "#file",
advanceOn: "dblclick",
popover: {
title: "Open the file",
instruction: "Double-click report.pdf .",
},
},
{
element: "#opened",
waitForElement: 1000,
popover: { title: "Opened", showButtons: ["next"] },
},
],
});
driverObj.drive();
```
Good to know:
- A double-click arrives as `click`, `click`, `dblclick`. Don't block clicks on a double-click step.
- `onInteraction` only sees the click. On the highlighted element and allowed elements, `pointerdown` has already reached your app, so returning `false` can't undo what it did, like closing a menu.
- Clicks on the popover are not reported, but they reach your app. Ignore them in a "click outside" handler with `event.target.closest(".driver-popover")`.
- Key presses are not reported, so typing always works.
- `nudge({ description })` changes the popover's own text instead of adding a line. `updatePopover()` does the same without the shake.
Clicks outside the highlighted element never reach your app. [How Clicks Are Handled](https://driverjs.com/docs/configuration.md#how-clicks-are-handled) has the details.
## Let the User Hover, Not Click
`disableActiveInteraction: true` turns off every pointer event on the element, so its tooltips stop working too. `"clicks"` keeps hover and blocks clicks, right-clicks and double-clicks. Hover the appointment, then click it.
```js
const driverObj = driver({
steps: [
{
element: "#appointment",
disableActiveInteraction: "clicks",
popover: {
title: "Appointment details",
description: "Rest your mouse on it to see the details.",
},
},
],
});
driverObj.drive();
```
`onInteraction` still sees the blocked clicks with region `"element"`, so you can point the user to the Next button. Don't combine it with an `advanceOn` that waits for a click: the step could never complete, and driver.js warns about it in the console.
## Let the User Use a Menu
When a step opens something outside the highlighted element, like a menu, list it in `allowedElements` so the user can use it. Below, the menu works, Delete is blocked, and closing the menu with Escape or a second click on More sends you back to the step that opens it.
```js
const driverObj = driver({
showButtons: ["next", "close"],
onElementMissing: "previousAction",
onInteraction: (element, step, { event, driver }) => {
if (event.target.closest("[data-action=delete]")) {
driver.nudge("Not Delete. Choose Archive .");
return false;
}
},
steps: [
{
element: "#more",
advanceOn: "click",
allowedElements: ".menu",
popover: {
title: "Open the menu",
instruction: "Click More .",
},
},
{
element: ".menu [data-action=archive]",
waitForElement: 500,
advanceOn: "click",
allowedElements: [".menu", "#more"],
popover: {
title: "Archive it",
instruction: "Choose Archive .",
},
},
{
element: "#archived",
waitForElement: 1000,
popover: { title: "Archived", showButtons: ["next"] },
},
],
});
driverObj.drive();
```
Allowed elements are raised above the overlay so they stay clickable. When one holds the highlighted element, like the menu around Archive, the element gets a ring instead of a cutout. Restyle it with the [raised highlight variables](https://driverjs.com/docs/theming.md#css-variables).
When the highlighted element leaves the page, `onElementMissing` decides what happens. `"previousAction"` goes back to the last action step whose element is still there, here the one that opens the menu. The other choices are in [Missing Elements](https://driverjs.com/docs/configuration.md#missing-elements).
## Recover From a Slow Load
When a step's `waitForElement` runs out, the tour shows that step without its element. Pass a function to `onElementMissing` to handle it: it runs with `cause: "timeout"`, and returning `false` keeps the user on the current step. The first load below is slow on purpose.
```js
const driverObj = driver({
showButtons: ["close"],
onElementMissing: (element, step, { cause, driver }) => {
if (cause === "timeout") {
driver.nudge({
description: "Still loading. Click Load report again.",
});
return false;
}
},
steps: [
{
element: "#load",
advanceOn: "click",
popover: {
title: "Load the report",
description: "Click Load report .",
},
},
{
element: "#report",
waitForElement: 1500,
popover: { title: "Loaded", showButtons: ["next"] },
},
],
});
driverObj.drive();
```
`onElementMissing: "previous"` does the same without the message.
> **Tip**: Always leave a way out, like the close button. iOS Safari never fires `contextmenu`, so a step that waits for a right-click should accept another event too.
---
# Headless Tours
> Run Driver.js tours with your own UI. The headless build finds each step's element, waits for it and moves through the steps, but draws nothing and leaves the page alone.
`driver.js/headless` runs a tour without any UI. It finds each step's element, waits for it, listens for `advanceOn` and calls your hooks. It draws no overlay or popover, adds no classes and never scrolls. You show the guidance yourself: a side panel, a chat message or your own tooltip component.
```js
import { driver } from "driver.js/headless";
const tour = driver({
steps: [
{ element: "#new-project", advanceOn: "click", data: { text: "Create a project" } },
{
element: "#project-name",
advanceOn: { event: "input", when: element => element.value.length > 2 },
data: { text: "Give it a name" },
},
{ element: "#save", advanceOn: "click", waitForElement: 3000, data: { text: "Save it" } },
],
onHighlighted: (element, step) => showGuide(element, step.data.text),
onDestroyed: () => hideGuide(),
});
tour.drive();
```
See [Build Your Own Tour UI](https://driverjs.com/docs/build-your-own-tour-ui.md) for four complete examples with live demos.
It takes the same config and steps as `driver.js` and returns the same [API](https://driverjs.com/docs/api.md), so you can switch a tour between the two. There is no stylesheet to import. The headless build is less than half the size of the full one.
## What still works
- Finding elements: selectors, elements and functions.
- [Missing elements](https://driverjs.com/docs/configuration.md#missing-elements): `waitForElement`, `waitForRemovedElement`, `skipMissingElement`, `onElementMissing` and `onWaitingForElement`.
- `onInteraction` for every click, with `region` telling the highlighted element, the `allowedElements` and the rest of the page apart. Nothing is blocked unless it returns `false`.
- `advanceOn` with `when` and `strict`, `advanceDelay` and `advance()`.
- Hooks: `onHighlightStarted`, `onHighlighted`, `onDeselected`, `onDestroyStarted`, `onDestroyed`, `onInteraction`, `onWaitingForElement` and `onElementReplaced`.
- Navigation: `drive()`, `moveNext()`, `movePrevious()`, `moveTo()`, `highlight()` and `destroy()`.
- A highlighted element that your framework re-renders is followed, and `advanceOn` listens on the new one. `onElementReplaced` gets the new element, so your UI can move to it.
To show that a step is waiting for its element, use `onWaitingForElement`. Its `signal` aborts when the wait ends.
```js
driver({
waitForElement: 5000,
onWaitingForElement: (element, step, opts) => {
setLoading(true);
opts.signal.addEventListener("abort", () => setLoading(false));
},
});
```
`getActiveElement()` returns the current step's element, or `undefined` for a step without one. `onHighlighted` runs as soon as the current call returns, not on an animation frame, so a tour keeps going in a background tab.
## What it leaves to you
- The overlay, popover and every option that styles them. `updatePopover()` and `nudge()` do nothing.
- Scrolling. Call `element.scrollIntoView()` in `onHighlighted` if you want it.
- Keyboard control. Arrow keys and Escape don't move or close the tour.
- Focus. It is not moved into a popover or back when the tour ends, and `focus` does nothing.
- Blocking clicks. `disableActiveInteraction` and `allowedElements` are ignored. A `strict` `advanceOn` and an `onInteraction` that returns `false` still hold back clicks.
Starting a tour ends any other tour from the same build. A headless tour and a full one come from different builds, so they can run at the same time.
## Without the headless build
If you use the full driver and only want it to stop scrolling, set `scrollIntoView: false` on the driver or on a step.
---
# Feature Hints
> Add pulsing hint beacons to your UI with Driver.js. Users click a beacon to open a popover explaining the feature. Style the beacons and popovers to match your product.
Hints are pulsing beacons that sit on the page. The user clicks one to open a popover, in any order. Nothing is blocked, so the page stays usable.
They are a separate entry with their own stylesheet. You don't need `driver.css` unless you also use tours.
```js
import { hints } from "driver.js/hints";
import "driver.js/dist/hints.css";
```
Each hint points at an element and describes it in a popover. The demo also turns on the optional overlay.
```js
const productHints = hints({
overlay: true,
overlayOpacity: 0.5,
hints: [
{
element: "#export-btn",
id: "export",
popover: {
title: "Export your data",
description: "Download this report as CSV or PDF.",
},
},
{
element: "#summary",
id: "summary",
beacon: { side: "left", align: "center" },
popover: {
title: "Auto-generated summary",
description: "Written for you from the quarter's numbers.",
side: "bottom",
},
},
],
});
productHints.show();
```
## Closing vs. dismissing
- Closing keeps the beacon. Clicking the beacon again, clicking outside or pressing Escape closes the popover, and the hint can be opened again.
- Dismissing removes the beacon. The _Got it_ button does it and runs `onDismiss`. Set `onButtonClick` to decide yourself what the button does.
Only one hint is open at a time.
## Remembering dismissals
Dismissals last until the page reloads. To keep them, give hints an `id` and save it in `onDismiss`. Dismiss a hint below, then load the page again.
```js
const saved = JSON.parse(localStorage.getItem("hints") ?? "[]");
const dismissed = new Set(saved);
const productHints = hints({
hints: allHints.filter(hint => !dismissed.has(hint.id)),
onDismiss: (element, hint) => {
dismissed.add(hint.id);
localStorage.setItem("hints", JSON.stringify([...dismissed]));
},
});
productHints.show();
```
## Dimming the page
`overlay: true` dims the page while a hint is open, like a tour step. The element is cut out and stays usable, the popover points at the element instead of the beacon, and a click on the dimmed page closes the hint.
```js
const productHints = hints({
overlay: true,
overlayColor: "#000",
overlayOpacity: 0.5,
hints: [
// ...
],
});
```
## Using hints alongside a tour
While a tour runs, the beacons hide. They come back when it ends. A hint can also start a tour from its button. Open the beacon below and take the tour.
```js
const tour = driver({
steps: [
// ...
],
});
const productHints = hints({
hints: [
{
element: "#whats-new",
id: "whats-new",
popover: {
title: "New dashboard",
description: "Want a quick walkthrough?",
buttonText: "Take the tour",
onButtonClick: (element, hint, { hints: instance }) => {
instance.close();
tour.drive();
},
},
},
],
});
```
For more buttons or your own markup, use `onPopoverRender`, like in [tours](https://driverjs.com/docs/custom-buttons.md).
## Styling
### Beacon placement
A beacon sits on an edge of its element: `side` picks the edge and `align` the position along it. The default is the top right corner. `offsetX` and `offsetY` move it by a number of pixels, where positive is right and down.
```js
const productHints = hints({
hints: [
{
element: "#dashboard",
beacon: { side: "top", align: "end", offsetX: -12, offsetY: 8 },
popover: { title: "Dashboard" },
},
],
});
```
### Beacon color and size
Beacons read CSS variables for their color and size. Set them on `.driver-hint` for all beacons, or on a class you give one beacon with `className`. All beacon variables and classes are in [Theming](https://driverjs.com/docs/theming.md#hints).
```css
/* All beacons */
.driver-hint {
--driver-hint-color: #e11d48;
--driver-hint-size: 28px;
}
/* Only beacons carrying a class */
.my-special-hint {
--driver-hint-color: #059669;
}
```
```js
const productHints = hints({
hints: [
{
element: "#export-btn",
beacon: { className: "my-special-hint" },
popover: { title: "A green beacon" },
},
],
});
```
### Static beacons
`animate: false` turns the pulse off. Users who prefer reduced motion never see it.
```js
const productHints = hints({
// For every hint. A hint's own beacon values win.
beacon: { animate: false },
hints: [
// ...
],
});
```
### Custom button text
`buttonText` changes the _Got it_ button, for all hints or in one hint's `popover`. `showButton: false` hides it, for hints you dismiss from code.
```js
const productHints = hints({
buttonText: "Thanks, understood",
hints: [
{
element: "#share-btn",
popover: {
title: "No button at all",
showButton: false,
},
},
],
});
```
### Theming the popover
Hint popovers are regular popovers, so `popoverClass` and everything in [Theming](https://driverjs.com/docs/theming.md#popover) apply.
```js
const productHints = hints({
popoverClass: "driverjs-theme",
hints: [
// ...
],
});
```
## Reference
- Every option: [Hints Configuration](https://driverjs.com/docs/configuration.md#hints-configuration)
- Every method: [API Reference](https://driverjs.com/docs/api.md#hints)
---
# Checklists
> Add an onboarding checklist to your app with Driver.js. Items launch product tours, follow links or wait for the user to do something, and tick themselves off as users make progress.
A checklist is a "Get started" widget in the corner of your app. Each item is one thing you want new users to do. An item can start a tour, open a link or run your code, and it ticks itself off once the user has done it.
Checklists are a separate entry. Their items run tours, so import `driver.css` as well:
```js
import { checklist } from "driver.js/checklist";
import "driver.js/dist/driver.css";
import "driver.js/dist/checklist.css";
```
Finish the tour below to tick its item. Close it early and the item stays open. _Connect GitHub_ in the mock dashboard ticks the second item.
```js
const onboarding = checklist({
id: "onboarding",
title: "Get started",
description: "Four steps to your first project.",
items: [
{
id: "tour",
title: "Take the tour",
tour: [
{
element: "#new-project",
popover: { title: "New Project", description: "..." },
},
{
element: "#connect-github",
popover: { title: "Connect GitHub", description: "..." },
},
],
},
{
id: "github",
title: "Connect GitHub",
completeWhen: () => user.githubConnected,
},
{
id: "invite",
title: "Invite a teammate",
action: () => openInviteModal(),
},
{
id: "docs",
title: "Read about saving progress",
href: "/docs/checklists#saving-progress",
},
],
});
onboarding.show();
```
## Items
Every item needs an `id`. Saved progress is a list of these ids, so keep them the same when you reword or reorder items. Missing and duplicate ids log a warning.
What a click on an item does depends on what it has:
- `tour`: the checklist closes and the tour starts. The item is ticked only
when the user finishes the tour; closing it early leaves the item open. The
checklist opens again when the tour ends either way. Pass an array of steps,
a full [driver configuration](https://driverjs.com/docs/configuration.md#driver-configuration), or
a `driver()` instance you created yourself; its own hooks keep working.
- `href`: rendered as a link. The item is ticked on click and the link
navigates as usual.
- `action`: your function runs with `(item, { checklist })` and the item is
ticked.
- None of these: the item is a plain row, ticked by `completeWhen` or by
calling `complete(id)`.
### Completing items from your app
For tasks done in your app, give the item a `completeWhen` function. The checklist ticks the item once it returns `true`. It is checked on `show()`, after the item's tour or action, and when you call `refresh()`.
```js
const onboarding = checklist({
id: "onboarding",
items: [
{
id: "github",
title: "Connect GitHub",
completeWhen: () => user.githubConnected,
},
],
});
// After the user connects GitHub somewhere in your app
onboarding.refresh();
```
On an item with a tour, link or action, `completeWhen` replaces the default: the item is ticked only when it returns `true`. To tick an item yourself, call `onboarding.complete("github")`.
### Letting users tick items off
Some tasks can't be detected, like "Watch the intro video". With `allowManualComplete` the check circle becomes a button, and users tick or untick items themselves. A click on the item's text still runs its tour, link or action.
```js
checklist({
id: "onboarding",
allowManualComplete: true,
items: [
{ id: "video", title: "Watch the intro video", href: "/intro" },
// Only ticked by finishing the tour, even with manual completion on.
{
id: "tour",
title: "Take the tour",
tour: steps,
allowManualComplete: false,
},
],
});
```
An item's own `allowManualComplete` wins. From code, use `complete(id)` and `uncomplete(id)`.
## Saving progress
The checklist stores nothing. Pass the ids that are already done as `completed`, and save them in `onProgress`, which runs on every change. Keep them in localStorage, your API or the user record.
```js
const onboarding = checklist({
id: "onboarding",
items,
completed: JSON.parse(localStorage.getItem("onboarding") ?? "[]"),
onProgress: ({ completed, done, total }) => {
localStorage.setItem("onboarding", JSON.stringify(completed));
},
});
onboarding.show();
```
## When everything is done
Once every item is done, the checklist can show a different title, description and launcher text. The demo starts with three of four items done, so click the last one.
```js
checklist({
id: "onboarding",
completeTitle: "You're all set! 🎉",
completeDescription: "Nice work. You're ready to go.",
completeLauncherText: "All done",
items,
});
```
The checklist stays on the page when it is done. To hide it, call `hide()` from `onComplete`. On later visits, check the saved progress before showing it:
```js
const onboarding = checklist({
id: "onboarding",
items,
completed: savedProgress,
onComplete: () => setTimeout(() => onboarding.hide(), 3000),
});
const { done, total } = onboarding.getProgress();
if (done < total) {
onboarding.show();
}
```
## Tracking events
`onEvent` gets everything that happens in the checklist, ready to send to your analytics. Open the checklist below, take the tour, and watch the events.
```js
checklist({
id: "onboarding",
items,
onEvent: event => {
// { kind: "checklist", id: "onboarding", type: "item_completed",
// itemId: "github", timestamp: 1760000000000 }
analytics.track(`checklist_${event.type}`, event);
},
});
```
The event types are `shown`, `hidden`, `opened`, `closed`, `item_started`,
`item_completed`, `item_uncompleted`, `tour_ended` (with the tour's [`reason`](https://driverjs.com/docs/configuration.md#why-a-tour-ended)),
`completed` and `reset`.
## Customizing
### Theme
Pass `className` to put your own class on the widget, then style its parts. This is the theme of the driver.js homepage:
```js
checklist({
id: "onboarding",
className: "checklist-brutalist",
items,
});
```
- [Checklist Themes](https://driverjs.com/docs/checklist-themes.md) has its CSS and more themes to copy.
- [Theming](https://driverjs.com/docs/theming.md#checklist) has the accent color variable and every class name.
### Position
`position` moves the widget to a corner: `"bottom-right"` (default), `"bottom-left"`, `"top-right"` or `"top-left"`.
`offset` sets the distance from the screen edges in pixels, for example to make room for a chat bubble:
```js
checklist({
id: "onboarding",
position: "bottom-right",
offset: { x: 20, y: 90 },
items,
});
```
The default is 20 pixels, or 12 on screens narrower than 480 pixels, where the panel also spans the width of the screen.
### Text
Every text of the widget can be changed. `progressText` and `launcherProgressText` replace `{{done}}`, `{{total}}`, `{{remaining}}` and `{{percent}}`.
```js
checklist({
id: "onboarding",
title: "Welcome aboard 👋",
description: "Finish these to unlock your workspace.",
launcherText: "Setup guide",
progressText: "{{done}}/{{total}} complete",
launcherProgressText: "{{done}} of {{total}}",
items,
});
```
### Your Own Launcher
`launcher: false` hides the floating button. Open the panel from your own button:
```js
const onboarding = checklist({ id: "onboarding", launcher: false, items });
onboarding.show();
document
.querySelector("#help-button")
.addEventListener("click", () => onboarding.toggle());
```
## Reference
- Every option: [Checklist Configuration](https://driverjs.com/docs/configuration.md#checklist-configuration)
- Every method: [API Reference](https://driverjs.com/docs/api.md#checklists)
---
# Checklist Themes
> Ready-made themes for Driver.js checklists: dark mode, gradient header, GIF banner, numbered steps, progress ring, cards, compact and a completion celebration. Copy the CSS and go.
Each theme is plain CSS on top of the default [checklist](https://driverjs.com/docs/checklists.md) styles. Copy its CSS into your stylesheet and pass its class name to the checklist:
```js
import { checklist } from "driver.js/checklist";
import "driver.js/dist/driver.css";
import "driver.js/dist/checklist.css";
import "./checklist-theme.css"; // The CSS you copied
checklist({
id: "onboarding",
className: "checklist-gradient",
items,
}).show();
```
Mix their rules or start your own from one. Every class name is listed in [Theming](https://driverjs.com/docs/theming.md#checklist-classes).
## Gradient Header
A bold, colored header that carries your brand. The launcher turns into a
gradient pill.
```css
.driver-checklist.checklist-gradient {
--driver-checklist-color: #7c3aed;
}
.driver-checklist.checklist-gradient .driver-checklist-launcher {
border: none;
border-radius: 999px;
background: linear-gradient(135deg, #7c3aed, #db2777);
box-shadow: 0 6px 20px rgba(124, 58, 237, 0.35);
}
.driver-checklist.checklist-gradient .driver-checklist-launcher-count {
padding: 2px 8px;
border-radius: 999px;
background-color: rgba(255, 255, 255, 0.25);
color: #fff;
}
.driver-checklist.checklist-gradient .driver-checklist-panel {
border: none;
border-radius: 16px;
box-shadow: 0 12px 32px rgba(76, 29, 149, 0.2);
}
.driver-checklist.checklist-gradient .driver-checklist-header {
padding: 18px 18px 16px;
background: linear-gradient(135deg, #7c3aed, #db2777);
color: #fff;
}
.driver-checklist.checklist-gradient .driver-checklist-title {
font-weight: 700;
}
.driver-checklist.checklist-gradient .driver-checklist-description,
.driver-checklist.checklist-gradient .driver-checklist-progress-text {
color: rgba(255, 255, 255, 0.85);
}
.driver-checklist.checklist-gradient .driver-checklist-close-btn {
color: rgba(255, 255, 255, 0.7);
}
.driver-checklist.checklist-gradient .driver-checklist-close-btn:hover {
color: #fff;
}
.driver-checklist.checklist-gradient .driver-checklist-progress-bar {
background-color: rgba(255, 255, 255, 0.3);
}
.driver-checklist.checklist-gradient .driver-checklist-progress-fill {
background-color: #fff;
}
.driver-checklist.checklist-gradient .driver-checklist-items {
padding-top: 8px;
}
```
## Cards
Each item in its own card, with a chevron on the ones that do something. Done
items turn green.
```css
.driver-checklist.checklist-cards {
--driver-checklist-color: #16a34a;
}
.driver-checklist.checklist-cards .driver-checklist-items {
display: flex;
flex-direction: column;
gap: 8px;
padding: 4px 14px 14px;
}
.driver-checklist.checklist-cards .driver-checklist-item {
align-items: center;
padding: 12px;
border: 1px solid #e5e5e5;
border-radius: 10px;
}
/* A chevron on items that do something when clicked. */
.driver-checklist.checklist-cards
.driver-checklist-item:has(
button.driver-checklist-item-trigger,
a.driver-checklist-item-trigger
)::after {
content: "";
flex-shrink: 0;
width: 7px;
height: 7px;
margin-right: 4px;
border: solid #a3a3a3;
border-width: 1.5px 1.5px 0 0;
transform: rotate(45deg);
}
.driver-checklist.checklist-cards
.driver-checklist-item:has(
button.driver-checklist-item-trigger:hover,
a.driver-checklist-item-trigger:hover,
button.driver-checklist-check
+ div.driver-checklist-item-trigger:hover,
.driver-checklist-item-trigger:focus-visible
) {
border-color: #d4d4d4;
background-color: #fafafa;
}
.driver-checklist.checklist-cards .driver-checklist-item-done {
border-color: #bbf7d0;
background-color: #f0fdf4;
}
.driver-checklist.checklist-cards .driver-checklist-item-done
.driver-checklist-item-title {
text-decoration: none;
}
```
## Numbered Steps
Numbers instead of empty circles, for checklists meant to be done in order.
CSS counters number the items, so there is nothing to add to the items
themselves.
```css
.driver-checklist.checklist-numbered .driver-checklist-items {
counter-reset: checklist-step;
}
/* The number sits on the title's baseline, whatever the font. */
.driver-checklist.checklist-numbered .driver-checklist-item {
counter-increment: checklist-step;
align-items: baseline;
}
/* The circle shows the step number until the item is done. */
.driver-checklist.checklist-numbered .driver-checklist-check {
display: flex;
align-items: center;
justify-content: center;
width: 22px;
height: 22px;
margin-top: 0;
border-color: #d4d4d4;
font-size: 12px;
font-weight: 600;
color: #525252;
}
.driver-checklist.checklist-numbered .driver-checklist-check::after {
content: counter(checklist-step);
}
/* Kept but hidden once done, so the circle still has a baseline
to align by. */
.driver-checklist.checklist-numbered .driver-checklist-item-done
.driver-checklist-check::after {
color: transparent;
}
.driver-checklist.checklist-numbered .driver-checklist-item-done
.driver-checklist-check {
border-color: var(--driver-checklist-color, #2d2d2d);
}
```
## Progress Ring
A ring around the launcher that fills up as items are done, with the number of
items left inside it. The checklist sets `--driver-checklist-progress` to the
progress as a percentage for the ring, `{{remaining}}` puts the count inside it,
and `{{percent}}` shows the percentage in the panel:
```js
checklist({
id: "onboarding",
className: "checklist-ring",
progressText: "{{percent}}% complete",
launcherProgressText: "{{remaining}}",
items,
});
```
```css
/* --driver-checklist-progress holds the progress as a percentage, so a
conic gradient can draw it as a ring around the launcher's count. */
.driver-checklist.checklist-ring {
--driver-checklist-color: #22c55e;
}
.driver-checklist.checklist-ring .driver-checklist-launcher {
gap: 10px;
padding: 6px 6px 6px 14px;
border-radius: 999px;
}
.driver-checklist.checklist-ring .driver-checklist-launcher-count {
display: grid;
place-items: center;
width: 32px;
height: 32px;
border-radius: 50%;
background:
radial-gradient(closest-side, #2d2d2d 78%, transparent 80% 100%),
conic-gradient(
#22c55e var(--driver-checklist-progress),
rgba(255, 255, 255, 0.2) 0
);
font-size: 12px;
font-weight: 600;
color: #fff;
}
.driver-checklist.checklist-ring .driver-checklist-progress-bar {
height: 8px;
border-radius: 4px;
}
.driver-checklist.checklist-ring .driver-checklist-progress-text {
order: -1;
font-weight: 600;
color: #16a34a;
}
```
## Compact
A small checklist that stays out of the way, for items that don't need a
description. The launcher counts what is left with `{{remaining}}`:
```js
checklist({
id: "onboarding",
className: "checklist-compact",
title: "Setup",
launcherProgressText: "{{remaining}} left",
items, // Titles only
});
```
```css
.driver-checklist.checklist-compact .driver-checklist-launcher {
padding: 7px 12px;
border-radius: 999px;
font-size: 13px;
}
@media (min-width: 481px) {
.driver-checklist.checklist-compact .driver-checklist-panel {
width: 260px;
}
}
.driver-checklist.checklist-compact .driver-checklist-header {
padding: 12px 14px 8px;
}
.driver-checklist.checklist-compact .driver-checklist-title {
font-size: 15px;
}
.driver-checklist.checklist-compact .driver-checklist-progress {
margin-top: 8px;
}
.driver-checklist.checklist-compact .driver-checklist-items {
padding: 0 6px 6px;
}
.driver-checklist.checklist-compact .driver-checklist-item {
gap: 8px;
padding: 6px 8px;
}
.driver-checklist.checklist-compact .driver-checklist-item-title {
font-size: 13px;
font-weight: 500;
}
.driver-checklist.checklist-compact .driver-checklist-check {
width: 14px;
height: 14px;
}
```
## GIF Banner
An image, GIF or animated illustration above the title, to make the welcome
feel friendly. The description accepts HTML, so the image goes there, and the
CSS moves it above the title:
```js
checklist({
id: "onboarding",
className: "checklist-media",
title: "Welcome to Foxbase",
description:
' ' +
"Four quick steps to get you going.
",
items,
});
```
```css
/* The image goes in the description, as HTML. These rules lift it
above the title as a banner, with the description text below. */
.driver-checklist.checklist-media .driver-checklist-header {
display: flex;
flex-direction: column;
}
.driver-checklist.checklist-media .driver-checklist-description {
display: contents;
}
.driver-checklist.checklist-media .driver-checklist-description img {
order: -1;
display: block;
width: 100%;
height: 140px;
margin-bottom: 12px;
border: 1px solid #ececec;
border-radius: 8px;
object-fit: cover;
}
.driver-checklist.checklist-media .driver-checklist-description p {
margin: 4px 0 0;
font-size: 14px;
line-height: 1.5;
}
.driver-checklist.checklist-media .driver-checklist-close-btn {
top: 22px;
right: 22px;
width: 26px;
height: 26px;
border-radius: 50%;
background-color: rgba(255, 255, 255, 0.9);
font-size: 16px;
line-height: 26px;
color: #2d2d2d;
}
```
## Midnight
A dark theme for dark apps, with a violet accent.
```css
.driver-checklist.checklist-midnight {
--driver-checklist-color: #a78bfa;
color: #f3f4f6;
}
.driver-checklist.checklist-midnight .driver-checklist-launcher {
border-color: #374151;
background-color: #111827;
color: #f9fafb;
}
.driver-checklist.checklist-midnight .driver-checklist-launcher:hover {
background-color: #1f2937;
}
.driver-checklist.checklist-midnight .driver-checklist-launcher-count {
color: #a78bfa;
}
.driver-checklist.checklist-midnight .driver-checklist-panel {
border-color: #1f2937;
background-color: #111827;
box-shadow: 0 12px 32px rgba(0, 0, 0, 0.35);
}
.driver-checklist.checklist-midnight .driver-checklist-description,
.driver-checklist.checklist-midnight .driver-checklist-progress-text,
.driver-checklist.checklist-midnight .driver-checklist-item-description {
color: #9ca3af;
}
.driver-checklist.checklist-midnight .driver-checklist-close-btn {
color: #6b7280;
}
.driver-checklist.checklist-midnight .driver-checklist-close-btn:hover {
color: #f9fafb;
}
.driver-checklist.checklist-midnight .driver-checklist-progress-bar {
background-color: #1f2937;
}
.driver-checklist.checklist-midnight .driver-checklist-check {
border-color: #4b5563;
}
.driver-checklist.checklist-midnight .driver-checklist-item-done
.driver-checklist-check {
border-color: #a78bfa;
}
.driver-checklist.checklist-midnight .driver-checklist-item-done
.driver-checklist-item-title {
color: #6b7280;
}
.driver-checklist.checklist-midnight
.driver-checklist-item:has(
button.driver-checklist-item-trigger:hover,
a.driver-checklist-item-trigger:hover,
button.driver-checklist-check
+ div.driver-checklist-item-trigger:hover,
.driver-checklist-item-trigger:focus-visible
) {
background-color: #1f2937;
}
```
## Celebration
A finished state that rewards the user. Once every item is done, the checklist
shows `completeTitle` and `completeDescription`, the launcher shows
`completeLauncherText`, and the CSS turns it green. This demo starts with three
of four items done, so click the last one to see it.
```js
checklist({
id: "onboarding",
className: "checklist-celebration",
completeTitle: "You're all set! 🎉",
completeDescription: "Nice work. You're ready to go.",
completeLauncherText: "All done",
items,
});
```
```css
/* The widget gets .driver-checklist-complete once every item is done. */
.driver-checklist.checklist-celebration.driver-checklist-complete {
--driver-checklist-color: #16a34a;
}
.driver-checklist.checklist-celebration.driver-checklist-complete
.driver-checklist-launcher {
border-color: #16a34a;
background-color: #16a34a;
}
.driver-checklist.checklist-celebration.driver-checklist-complete
.driver-checklist-header {
background-color: #f0fdf4;
}
.driver-checklist.checklist-celebration.driver-checklist-complete
.driver-checklist-title {
font-weight: 600;
color: #15803d;
animation: checklist-celebration-pop 400ms ease-out;
}
@keyframes checklist-celebration-pop {
from {
opacity: 0;
transform: scale(0.95);
}
}
```
For confetti or a "You did it" modal, use the `onComplete` hook. It fires once
when the last item is done:
```js
checklist({
id: "onboarding",
items,
onComplete: () => confetti(),
});
```
## Brutalist
The theme of the driver.js homepage: thick borders, hard shadows and a yellow
header.
```css
/* The theme of the driver.js homepage. */
.driver-checklist.checklist-brutalist {
--driver-checklist-color: #000;
}
.driver-checklist.checklist-brutalist .driver-checklist-launcher {
padding: 10px 16px;
border: 2px solid #000;
border-radius: 12px;
background-color: #fde047;
color: #000;
box-shadow: 3px 3px 0 0 #000;
}
.driver-checklist.checklist-brutalist .driver-checklist-launcher:hover {
background-color: #facc15;
}
.driver-checklist.checklist-brutalist .driver-checklist-launcher:active {
transform: translate(2px, 2px);
box-shadow: 1px 1px 0 0 #000;
}
.driver-checklist.checklist-brutalist .driver-checklist-launcher-count {
padding: 2px 7px;
border-radius: 999px;
background-color: #000;
color: #fde047;
}
.driver-checklist.checklist-brutalist .driver-checklist-panel {
border: 2px solid #000;
border-radius: 12px;
box-shadow: 4px 4px 0 0 #000;
}
.driver-checklist.checklist-brutalist .driver-checklist-header {
border-bottom: 2px solid #000;
background-color: #fde047;
}
.driver-checklist.checklist-brutalist .driver-checklist-title {
font-weight: 700;
color: #000;
}
.driver-checklist.checklist-brutalist .driver-checklist-items {
padding-top: 7px;
}
.driver-checklist.checklist-brutalist .driver-checklist-description,
.driver-checklist.checklist-brutalist .driver-checklist-progress-text,
.driver-checklist.checklist-brutalist .driver-checklist-close-btn {
color: rgba(0, 0, 0, 0.7);
}
.driver-checklist.checklist-brutalist .driver-checklist-progress-bar {
height: 10px;
border: 2px solid #000;
background-color: #fff;
}
.driver-checklist.checklist-brutalist .driver-checklist-progress-fill {
border-radius: 0;
}
.driver-checklist.checklist-brutalist .driver-checklist-check {
border-color: #000;
}
.driver-checklist.checklist-brutalist
.driver-checklist-item:has(
button.driver-checklist-item-trigger:hover,
a.driver-checklist-item-trigger:hover,
button.driver-checklist-check
+ div.driver-checklist-item-trigger:hover,
.driver-checklist-item-trigger:focus-visible
) {
background-color: #fef9c3;
}
```
---
# All Recipes
> Short, copy-ready Driver.js recipes for common jobs: first-run onboarding, teaching a form or a menu, resuming tours, confirming exits, analytics, frameworks and theming.
Each recipe is one job, with a live demo where it helps and the code to copy. The guides explain the features; the recipes put them together.
## Onboard New Users
- [First-Run Onboarding](https://driverjs.com/docs/first-run-onboarding.md): show a tour once on the first visit, with a replay button.
- [Getting-Started Checklist](https://driverjs.com/docs/getting-started-checklist.md): a checklist whose items each launch a short tour.
- [Announce a Feature](https://driverjs.com/docs/announce-a-feature.md): point out something new once, or with a hint that stays dismissed.
- [Start From a Help Menu](https://driverjs.com/docs/start-from-a-help-menu.md): "Take the tour" starts at the step for the current screen.
## Teach a Task
- [Teach a Form](https://driverjs.com/docs/teach-a-form.md): explain each field, or move on only when a field is valid.
- [Walk Through a Menu](https://driverjs.com/docs/walk-through-a-menu.md): open a dropdown, pick an item, recover when it closes.
- [Steps Inside a Dialog](https://driverjs.com/docs/steps-inside-a-dialog.md): run steps inside a modal and come back to the page.
- [Wait for a Save](https://driverjs.com/docs/wait-for-a-save.md): hold a step until your app finishes, then show it's done.
- [Right-Click and Double-Click Steps](https://driverjs.com/docs/right-click-and-double-click.md): accept only the gesture the step teaches.
## Keep Progress
- [Resume a Tour](https://driverjs.com/docs/resume-a-tour.md): pick up at the step where the user left.
- [Multi-Page Tours](https://driverjs.com/docs/multi-page-tours.md): continue a tour after a page load or route change.
## Control How a Tour Ends
- [Confirm Before Closing](https://driverjs.com/docs/confirm-before-closing.md): ask before an early exit, or don't allow one.
- [Track Tour Analytics](https://driverjs.com/docs/track-tour-analytics.md): finished or closed, and the step where people quit.
## Fit Your App
- [React and Vue](https://driverjs.com/docs/react-and-vue.md): set up and clean up in React, Vue and Next.js.
- [Custom Buttons](https://driverjs.com/docs/custom-buttons.md): add Skip and Restart, rename and translate buttons.
- [Match Your Brand](https://driverjs.com/docs/match-your-brand.md): dark and brand themes with a class and CSS variables.
- [Build Your Own Tour UI](https://driverjs.com/docs/build-your-own-tour-ui.md): a checklist panel, a chat assistant, a custom spotlight and form hints, all headless.
---
# First-Run Onboarding
> Show a Driver.js tour once, on a user's first visit, remember that they've seen it, and give them a button to replay it.
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());
```
- `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](https://driverjs.com/docs/track-tour-analytics.md)).
- 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](https://driverjs.com/docs/react-and-vue.md).
**Uses**: [`drive()`](https://driverjs.com/docs/api.md#starting-and-stopping), [`onDestroyed`](https://driverjs.com/docs/configuration.md#hooks), [`showProgress`](https://driverjs.com/docs/tour-basics.md#tour-progress)
---
# Teach a Form
> Explain a form field by field with Driver.js highlights, or walk users through filling it in with steps that only move on when each field is valid.
Two ways to help with a form: explain each field as the user reaches it, or walk them through filling it in and only move on when a field is right.
## Explain Each Field
Call `highlight()` on focus to show help next to the field the user is in. Focus the fields below.
```js
const driverObj = driver({
stagePadding: 0,
onDestroyed: () => document.activeElement?.blur(),
});
const help = {
"#name": { title: "Name", description: "Your full name" },
"#education": { title: "Education", description: "Degree" },
"#age": { title: "Age", description: "In years" },
"#address": { title: "Address", description: "Street, city" },
};
Object.entries(help).forEach(([selector, popover]) => {
const element = document.querySelector(selector);
element.addEventListener("focus", () => {
driverObj.highlight({ element, popover });
});
});
document
.querySelector("#submit-btn")
.addEventListener("focus", () => driverObj.destroy());
```
## Fill It In Step by Step
`advanceOn` with `when` checks the field on every event, so the step completes the moment the value is valid. `advanceDelay` shows the done state before moving on.
```js
const driverObj = driver({
showButtons: ["next", "close"],
steps: [
{
element: "#password",
advanceOn: {
event: "input",
when: element => element.value.length >= 8,
},
advanceDelay: 800,
popover: {
title: "Choose a password",
instruction: "Type at least 8 characters.",
},
},
{
element: "#terms",
advanceOn: "change",
popover: {
title: "The fine print",
instruction: "Accept the terms.",
},
},
{
element: "#submit",
advanceOn: "click",
popover: {
title: "Create the account",
instruction: "Click Create account .",
},
},
{
element: "#created",
waitForElement: 1000,
popover: {
title: "Account created",
showButtons: ["next"],
},
},
],
});
driverObj.drive();
```
To say what's wrong instead of waiting, call `driver.nudge("...")` from `when` and return `false`, like the email step in [Action-Driven Tours](https://driverjs.com/docs/action-driven-tours.md).
**Uses**: [`highlight()`](https://driverjs.com/docs/simple-highlight.md), [`advanceOn`](https://driverjs.com/docs/configuration.md#advanceon), [`popover.instruction`](https://driverjs.com/docs/action-driven-tours.md#make-the-user-act), [`advanceDelay`](https://driverjs.com/docs/action-driven-tours.md#show-success-before-moving-on)
---
# Walk Through a Menu
> Guide users through a Driver.js tour that opens a dropdown and picks an item, keeps the menu usable, and recovers when the menu closes.
Use this when the feature you're teaching sits behind a dropdown. The user opens the menu and picks the item themselves, and the tour goes back a step if the menu closes.
```js
const driverObj = driver({
showButtons: ["next", "close"],
onElementMissing: "previousAction",
steps: [
{
element: "#account",
advanceOn: "click",
allowedElements: ".account-menu",
popover: {
title: "Your account",
instruction: "Click Account .",
},
},
{
element: ".account-menu [data-item=settings]",
waitForElement: 500,
advanceOn: "click",
allowedElements: [".account-menu", "#account"],
popover: {
title: "Open settings",
instruction: "Choose Settings .",
},
},
{
element: "#settings-title",
waitForElement: 1000,
popover: { title: "Settings", showButtons: ["next"] },
},
],
});
driverObj.drive();
```
- `allowedElements` lets clicks reach the menu, which sits outside the highlighted element. Everything else on the page stays blocked.
- The open menu sits above the overlay so it stays usable, and the item to pick gets a ring instead of a cutout. Restyle it with the [raised highlight variables](https://driverjs.com/docs/theming.md#css-variables).
- `waitForElement` covers the time the menu takes to open.
- When the highlighted item leaves the page, because the user picked another item or pressed Escape, `"previousAction"` goes back to the step that opens the menu.
To block one item with a message, like Delete, see [Let the User Use a Menu](https://driverjs.com/docs/action-driven-tours.md#let-the-user-use-a-menu).
**Uses**: [`allowedElements`](https://driverjs.com/docs/configuration.md#allowedelements), [`onElementMissing`](https://driverjs.com/docs/configuration.md#missing-elements), [`advanceOn`](https://driverjs.com/docs/configuration.md#advanceon), [`waitForElement`](https://driverjs.com/docs/interactive-tours.md#wait-for-elements)
---
# Steps Inside a Dialog
> Run Driver.js tour steps inside a modal dialog: wait for it to open, dim the dialog like the page, and move back to the page when it closes.
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 New project .",
},
},
{
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 Create .",
},
},
{
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`](https://driverjs.com/docs/interactive-tours.md#wait-for-elements), [`advanceOn`](https://driverjs.com/docs/configuration.md#advanceon), [`popover.instruction`](https://driverjs.com/docs/action-driven-tours.md#make-the-user-act)
---
# Wait for a Save
> Keep a Driver.js tour on a step until your app finishes a save or a request, show a done state, then move on. Or load data before the next step.
Use this when the click is not the end of it: a save, an upload or a request has to finish before the next step makes sense. The step waits for your app, shows a done state, then moves on.
```js
const driverObj = driver({
showButtons: ["next", "close"],
steps: [
{
element: "#save",
advanceDelay: 600,
onHighlighted: (element, step, { signal, driver }) => {
window.addEventListener(
"profile-saved",
() => driver.advance(),
{ signal }
);
},
popover: {
title: "Save your profile",
instruction: "Click Save .",
},
},
{
element: "#saved",
popover: { title: "Saved", showButtons: ["next"] },
},
],
});
driverObj.drive();
```
Your app fires the event when the request comes back:
```js
async function saveProfile(profile) {
await fetch("/api/profile", {
method: "POST",
body: JSON.stringify(profile),
});
window.dispatchEvent(new Event("profile-saved"));
}
```
- `advance()` completes the step as if the user did it. With `advanceDelay`, the instruction turns green for the pause first.
- `onHighlighted` gets a `signal` that aborts when the step is left, so the listener removes itself.
## When Next Does the Work
To load something before the next step, take over the Next button with `onNextClick` and call `moveNext()` when you're ready. `updatePopover()` shows that it's loading in the meantime.
```js
const driverObj = driver({
steps: [
{
element: "#reports",
popover: {
title: "Your weekly report",
description: "Next loads the report first.",
onNextClick: async () => {
driverObj.updatePopover({
nextBtnText: "Loading…",
disableButtons: ["next"],
});
await loadReport();
driverObj.moveNext();
},
},
},
{
element: "#report",
popover: { title: "Here it is" },
onDeselected: () => unloadReport(),
},
],
});
```
`onNextClick` replaces the button's default action, so the tour only moves when you call `moveNext()`. `onPrevClick` works the same way for going back.
**Uses**: [`advance()`](https://driverjs.com/docs/api.md#navigation), [`advanceDelay`](https://driverjs.com/docs/action-driven-tours.md#show-success-before-moving-on), [`onHighlighted`](https://driverjs.com/docs/configuration.md#hooks), [`onNextClick`](https://driverjs.com/docs/popover.md#event-handlers), [`updatePopover()`](https://driverjs.com/docs/api.md#changing-the-popover)
---
# Resume a Tour
> Save the step a user was on when they closed a Driver.js tour, and pick up from there the next time.
Use this for a long tour people may not finish in one go. Save the step they were on when they left, and start from it next time.
Close the tour below on any step, then start it again.
```js
const STEP_KEY = "tour-step";
const driverObj = driver({
showProgress: true,
steps: [
{ element: "#overview", popover: { title: "Overview" } },
{ element: "#reports", popover: { title: "Reports" } },
{ element: "#team", popover: { title: "Team" } },
{ element: "#settings", popover: { title: "Settings" } },
],
onDestroyed: (element, step, { reason, index }) => {
if (reason === "done") {
localStorage.removeItem(STEP_KEY);
} else {
localStorage.setItem(STEP_KEY, String(index));
}
},
});
driverObj.drive(Number(localStorage.getItem(STEP_KEY) ?? 0));
```
`onDestroyed` gets the `index` of the step the user was on and the `reason` the tour ended. A finished tour clears the saved step, so it starts from the beginning next time.
For a tour that continues on another page, see [Multi-Page Tours](https://driverjs.com/docs/multi-page-tours.md).
**Uses**: [`drive(index)`](https://driverjs.com/docs/api.md#starting-and-stopping), [`onDestroyed`](https://driverjs.com/docs/configuration.md#hooks), [`reason`](https://driverjs.com/docs/configuration.md#why-a-tour-ended)
---
# Multi-Page Tours
> Continue a Driver.js tour across page loads or client-side routes: save the step, let the app navigate, and resume on the next page.
Use this when the tour has to follow the user to another page, like from the dashboard into settings. A driver lives on one page and a page load destroys it, so save the step to resume at, let the app navigate, and start the tour from that step on the next page.
On the step whose click navigates, `advanceOn: "click"` completes the step and `onNextClick` saves the progress instead of moving on. The link's own click still navigates.
Start the tour below. It walks over to Resume a Tour and continues there.
```js
import { driver } from "driver.js";
import "driver.js/dist/driver.css";
const TOUR_KEY = "app-tour";
function saveProgress(step, page) {
const progress = { step, page, savedAt: Date.now() };
sessionStorage.setItem(TOUR_KEY, JSON.stringify(progress));
}
export function createTour() {
let isNavigating = false;
const driverObj = driver({
steps: [
{ element: "#reports", popover: { title: "Reports" } },
{
element: "#settings-link",
advanceOn: "click",
popover: {
title: "Open Settings",
instruction: "Click Settings .",
onNextClick: () => {
isNavigating = true;
saveProgress(2, "/settings");
driverObj.destroy();
},
},
},
// On the settings page
{
element: "#profile-form",
waitForElement: 5000,
popover: {
title: "Your Profile",
onPrevClick: () => {
isNavigating = true;
saveProgress(1, "/reports");
driverObj.destroy();
location.assign("/reports");
},
},
},
{ element: "#save-settings", popover: { title: "Save" } },
],
onDestroyed: () => {
if (!isNavigating) {
sessionStorage.removeItem(TOUR_KEY);
}
},
});
return driverObj;
}
```
Going back works the same way in reverse. On the first step of the new page, `onPrevClick` saves the step that sends the user over, the link step, and navigates back. It also runs for the left arrow key. Try Previous on "Same tour, new page" in the demo.
On every page load, read the saved step once and resume only on the page it was saved for:
```js
const saved = JSON.parse(sessionStorage.getItem(TOUR_KEY));
sessionStorage.removeItem(TOUR_KEY);
const isFresh = saved && Date.now() - saved.savedAt < 300_000;
if (isFresh && saved.page === location.pathname) {
createTour().drive(saved.step);
}
```
- The saved step is read once and removed, so the tour never starts on a later visit, after a reload or after the browser's back button. Only the tour's own Previous takes it back a page.
- The `page` and `savedAt` checks keep it from popping up when the user ends up somewhere else, or comes back after more than five minutes.
- `sessionStorage` keeps it to this tab. Use `localStorage` if the next page may open in a new tab.
- `waitForElement` on the first resumed step covers the time the new page takes to render.
- `onDestroyed` clears the saved step when the tour is finished or closed before the user navigates.
- In a single-page app, run the resume code where a page mounts: an effect in React or Vue, a route hook, or `document.addEventListener("astro:page-load", ...)` with Astro's client router. Navigate with your router instead of `location.assign()`. The `destroy()` before navigating matters there: without it the old page's tour stays on screen.
To let users pick a tour up where they closed it, see [Resume a Tour](https://driverjs.com/docs/resume-a-tour.md).
**Uses**: [`drive(index)`](https://driverjs.com/docs/api.md#starting-and-stopping), [`advanceOn`](https://driverjs.com/docs/configuration.md#advanceon), [`onNextClick` and `onPrevClick`](https://driverjs.com/docs/popover.md#event-handlers), [`waitForElement`](https://driverjs.com/docs/interactive-tours.md#wait-for-elements), [`onDestroyed`](https://driverjs.com/docs/configuration.md#hooks)
---
# Confirm Before Closing
> Ask users to confirm before a Driver.js tour closes early, or stop them from leaving a tour they have to finish.
Use this when leaving halfway would lose something, like a setup the user has to finish. Ask before the tour closes early, or take the way out away entirely.
## Confirm on Exit
`onDestroyStarted` runs when the tour is about to end. Once you set it, the tour only ends when you call `destroy()`. The example only asks when the user leaves early.
```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" } },
],
onDestroyStarted: (element, step, { reason }) => {
if (reason === "done" || confirm("Are you sure?")) {
driverObj.destroy();
}
},
});
driverObj.drive();
```
`reason` tells a finished tour (`"done"`) apart from one the user is leaving. Use your own modal instead of `confirm()` the same way: call `destroy()` when the user agrees.
## Prevent Exit
`allowClose: false` removes the close button and turns off Escape and overlay clicks, so the only way out is to finish the tour.
```js
const driverObj = driver({
allowClose: false,
showProgress: true,
steps: [
{ element: "#search", popover: { title: "Search" } },
{ element: "#export", popover: { title: "Export" } },
],
});
driverObj.drive();
```
To keep the close button and only ignore clicks on the overlay, use `overlayClickBehavior: "none"` instead.
**Uses**: [`onDestroyStarted`](https://driverjs.com/docs/configuration.md#hooks), [`reason`](https://driverjs.com/docs/configuration.md#why-a-tour-ended), [`allowClose`](https://driverjs.com/docs/configuration.md#driver-configuration), [`overlayClickBehavior`](https://driverjs.com/docs/configuration.md#overlayclickbehavior)
---
# Announce a Feature
> Point out a new feature once with a Driver.js highlight, or leave a hint beacon on it that stays dismissed after the user has seen it.
Use this to tell existing users about something new without a full tour. Show it once and remember that they've seen it.
## Highlight It Once
Load the page below, close the popover, then load it again.
```js
const SEEN_KEY = "seen-pdf-export";
if (!localStorage.getItem(SEEN_KEY)) {
const driverObj = driver({
onDestroyed: () => localStorage.setItem(SEEN_KEY, "1"),
});
driverObj.highlight({
element: "#export-pdf",
popover: {
title: "New: export to PDF",
description: "Download any report as a PDF.",
showButtons: ["close"],
},
});
}
```
The page is dimmed until the user closes the popover. The highlighted button still works, so they can try it right away.
## Or Leave a Hint
A hint doesn't interrupt. The beacon pulses on the new feature until the user dismisses it with _Got it_, and `onDismiss` keeps it dismissed. Load the page, dismiss a hint, then load it again.
```js
import { hints } from "driver.js/hints";
import "driver.js/dist/hints.css";
const KEY = "dismissed-hints";
const dismissed = JSON.parse(localStorage.getItem(KEY) ?? "[]");
const newFeatures = [
{
id: "export-pdf",
element: "#export-pdf",
popover: {
title: "New: export to PDF",
description: "Download any report as a PDF.",
},
},
];
const productHints = hints({
hints: newFeatures.filter(h => !dismissed.includes(h.id)),
onDismiss: (element, hint) => {
dismissed.push(hint.id);
localStorage.setItem(KEY, JSON.stringify(dismissed));
},
});
productHints.show();
```
Add the next feature to `newFeatures` with its own `id`, and only users who haven't seen it get a beacon.
**Uses**: [`highlight()`](https://driverjs.com/docs/simple-highlight.md), [`onDestroyed`](https://driverjs.com/docs/configuration.md#hooks), [hints](https://driverjs.com/docs/hints.md#remembering-dismissals)
---
# React and Vue
> Use Driver.js in React, Vue and Next.js: create the driver once the elements are on the page, keep it client-side, and destroy it on unmount.
Driver.js works on plain DOM elements, so it needs no wrapper. Create the driver once the elements are on the page, and destroy it when the component goes away.
## React
```jsx
import { useEffect, useRef } from "react";
import { driver } from "driver.js";
import "driver.js/dist/driver.css";
export function Dashboard() {
const driverRef = useRef(null);
useEffect(() => {
driverRef.current = driver({
steps: [
{ element: "#new-project", popover: { title: "New" } },
{ element: "#invite", popover: { title: "Invite" } },
],
});
return () => driverRef.current.destroy();
}, []);
return (
New project
Invite
driverRef.current.drive()}>
Take the tour
);
}
```
## Vue
```vue
New project
Invite
Take the tour
```
## Next.js
A tour runs in the browser, so put it in a client component. Importing `driver.js` when the tour starts keeps it out of the server render and out of the page's first load.
```tsx
"use client";
import { useEffect, useRef } from "react";
import type { Driver } from "driver.js";
import "driver.js/dist/driver.css";
export function TourButton() {
const driverRef = useRef(null);
useEffect(() => {
return () => driverRef.current?.destroy();
}, []);
async function startTour() {
const { driver } = await import("driver.js");
driverRef.current = driver({
steps: [
{ element: "#new-project", popover: { title: "New" } },
{ element: "#invite", popover: { title: "Invite" } },
],
});
driverRef.current.drive();
}
return Take the tour ;
}
```
With the Pages Router, the same component works as is. To start a tour on load instead of on a click, call `startTour()` from the `useEffect`.
## Good to Know
- A step's `element` is looked up when the step starts, so selectors can point at elements that render later.
- When your framework replaces a highlighted element, the step [follows the new one](https://driverjs.com/docs/interactive-tours.md#elements-that-re-render).
- Prefer selectors over refs in steps: a selector finds the new element after a re-render, a stored element doesn't.
**Uses**: [`driver()`](https://driverjs.com/docs/configuration.md), [`drive()` and `destroy()`](https://driverjs.com/docs/api.md#starting-and-stopping)
---
# Start From a Help Menu
> Add a Take the tour item to your help menu that starts a Driver.js tour at the step for the screen the user is on.
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));
});
```
- 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()`](https://driverjs.com/docs/api.md#navigation), [step `data`](https://driverjs.com/docs/configuration.md#step-configuration), [`onHighlighted`](https://driverjs.com/docs/configuration.md#hooks)
---
# Right-Click and Double-Click Steps
> Teach a right-click menu or a double-click with Driver.js action steps that accept only that gesture and block the others.
Use this when the feature hides behind a gesture, like a context menu or a double-click to open. With `strict: true` the step takes only that gesture: a plain click on the file is blocked and shakes the popover instead of doing something else.
```js
const driverObj = driver({
showButtons: ["close"],
onElementMissing: "previousAction",
steps: [
{
element: "#file",
advanceOn: { event: "contextmenu", strict: true },
allowedElements: ".file-menu",
popover: {
title: "Copy the file",
instruction: "Right-click report.pdf .",
},
},
{
element: ".file-menu [data-action=duplicate]",
waitForElement: 500,
advanceOn: "click",
allowedElements: ".file-menu",
popover: {
title: "Duplicate it",
instruction: "Choose Duplicate .",
},
},
{
element: "#file-copy",
waitForElement: 1000,
advanceOn: { event: "dblclick", strict: true },
popover: {
title: "Open the copy",
instruction: "Double-click report copy.pdf .",
},
},
],
});
driverObj.drive();
```
- Your app's own `contextmenu` and `dblclick` handlers run as usual. The step completes after them.
- `strict` blocks the other clicks on the element only. Clicks in `allowedElements`, like the menu, still work.
- iOS Safari never fires `contextmenu`. On touch devices, accept another event too, like `["contextmenu", "dblclick"]`, or offer a button that opens the same menu.
**Uses**: [`advanceOn` with `strict`](https://driverjs.com/docs/action-driven-tours.md#accept-only-the-right-gesture), [`allowedElements`](https://driverjs.com/docs/configuration.md#allowedelements), [`onElementMissing`](https://driverjs.com/docs/configuration.md#missing-elements)
---
# Track Tour Analytics
> Find out whether users finished a Driver.js tour or closed it, and on which step they left, and send it to your analytics.
Use this to see whether people finish your tour, and where they give up when they don't. Run the tour below, then finish it or leave it early, and watch the events come in.
```js
const driverObj = driver({
showProgress: true,
steps: [
// ...
],
onHighlighted: (element, step, { index }) => {
analytics.track("tour_step_viewed", { step: index + 1 });
},
onDestroyed: (element, step, { reason, index }) => {
analytics.track("tour_ended", { reason, step: index + 1 });
},
});
driverObj.drive();
```
`onDestroyed` gets a `reason`:
- `"done"`: the user moved past the last step
- `"close"`, `"escape"` or `"overlay"`: the user left early
- `"replaced"`: another tour or highlight started
- `"api"`: your code called `destroy()`
A `destroy()` you call from a hook keeps the reason of the user action that started it, so a [Confirm on Exit](https://driverjs.com/docs/confirm-before-closing.md) hook still reports `"close"`, not `"api"`.
Count `tour_ended` events with `reason: "done"` to get your completion rate, and the `step` of the others to see where people leave.
**Uses**: [`onDestroyed`](https://driverjs.com/docs/configuration.md#hooks), [`reason`](https://driverjs.com/docs/configuration.md#why-a-tour-ended), [`onHighlighted`](https://driverjs.com/docs/configuration.md#hooks)
---
# Getting-Started Checklist
> Build a Driver.js getting-started checklist whose items each launch a short tour and tick themselves off when the tour is finished.
Use this instead of one long onboarding tour. Each item is a short tour of one task, users take them in any order, and finished tours tick their item.
Open the checklist and start an item. Finish its tour to tick it, or close it early and the item stays open.
```js
import { checklist } from "driver.js/checklist";
import "driver.js/dist/driver.css";
import "driver.js/dist/checklist.css";
const KEY = "get-started";
const onboarding = checklist({
id: "get-started",
title: "Get started",
items: [
{
id: "project",
title: "Create a project",
tour: [
{ element: "#new-project", popover: { title: "New" } },
],
},
{
id: "invite",
title: "Invite your team",
tour: [
{ element: "#invite", popover: { title: "Invite" } },
{ element: "#members", popover: { title: "Members" } },
],
},
{
id: "billing",
title: "Add billing details",
tour: [
{ element: "#billing", popover: { title: "Billing" } },
],
},
],
completed: JSON.parse(localStorage.getItem(KEY) ?? "[]"),
onProgress: ({ completed }) => {
localStorage.setItem(KEY, JSON.stringify(completed));
},
});
onboarding.show();
```
- `tour` takes steps, a full driver configuration or a `driver()` instance. The checklist closes while the tour runs and opens again when it ends.
- `completed` and `onProgress` keep the ticks across visits. The demo above leaves them out, so it starts fresh on reload.
- For tasks done in your app rather than in a tour, use `completeWhen` instead. See [Checklists](https://driverjs.com/docs/checklists.md#completing-items-from-your-app).
**Uses**: [Checklists](https://driverjs.com/docs/checklists.md), [saving progress](https://driverjs.com/docs/checklists.md#saving-progress), [Checklist Themes](https://driverjs.com/docs/checklist-themes.md)
---
# Custom Buttons
> Add Skip and Restart buttons to Driver.js popovers, rename the built-in buttons, and translate them for other languages.
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";
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();
```
The parts of the popover you can reach are listed in [Theming](https://driverjs.com/docs/theming.md#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} →`,
prevBtnText: `← ${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`](https://driverjs.com/docs/configuration.md#hooks), [button text](https://driverjs.com/docs/popover.md#change-button-text), [`progressText`](https://driverjs.com/docs/tour-basics.md#tour-progress), [API](https://driverjs.com/docs/api.md)
---
# Match Your Brand
> Give Driver.js popovers a dark theme or your brand colors with a popover class, a few CSS rules and the CSS variables.
Use this to make tours look like part of your product. A class on the popover scopes the CSS, and the CSS variables cover the action-step parts. Pick a theme below and run the tour.
```js
const driverObj = driver({
popoverClass: "brand-theme",
overlayColor: "#1e1b4b",
steps: [
// ...
],
});
driverObj.drive();
```
```css
.driver-popover.brand-theme {
background: #4f46e5;
color: #e0e7ff;
border-radius: 12px;
--driver-instruction-background: #4338ca;
--driver-instruction-indicator-color: #fde047;
}
.brand-theme .driver-popover-title {
color: #fff;
}
/* The arrow is a border: color the side it points from */
.brand-theme .driver-popover-arrow-side-top {
border-top-color: #4f46e5;
}
.brand-theme .driver-popover-arrow-side-bottom {
border-bottom-color: #4f46e5;
}
.brand-theme .driver-popover-arrow-side-left {
border-left-color: #4f46e5;
}
.brand-theme .driver-popover-arrow-side-right {
border-right-color: #4f46e5;
}
.brand-theme .driver-popover-footer-btn {
background: #fff;
color: #4338ca;
border: 0;
border-radius: 999px;
text-shadow: none;
}
```
For a dark theme, use the same rules with dark colors: `#18181b` for the popover and arrow, `#27272a` for the buttons and the instruction row, and white text.
Hints and checklists take the same approach with `--driver-hint-color` and `--driver-checklist-color`.
**Uses**: [`popoverClass`](https://driverjs.com/docs/theming.md#popover), [CSS variables](https://driverjs.com/docs/theming.md#css-variables), [`overlayColor`](https://driverjs.com/docs/theming.md#overlay), [Checklist Themes](https://driverjs.com/docs/checklist-themes.md)
---
# Build Your Own Tour UI
> Four tours with completely different UIs, built on driver.js/headless: a checklist panel, a chat assistant, a hand-drawn spotlight and hints inside a form. Live demos with the full code.
Use this when the popover isn't the right shape for your product. With [`driver.js/headless`](https://driverjs.com/docs/headless-tours.md), driver.js still runs the tour: it finds each element, waits for it and notices when the user does the step. Everything you see is yours.
The four tours below use the same engine with four very different UIs. The code under each demo is the exact code it runs.
## How Far to Go
| You want to... | Use |
| --- | --- |
| Use your colors and fonts on the popover | [Match Your Brand](https://driverjs.com/docs/match-your-brand.md), [Theming](https://driverjs.com/docs/theming.md) |
| Add, rename or translate buttons | [Custom Buttons](https://driverjs.com/docs/custom-buttons.md) |
| Change the popover's markup | [`onPopoverRender`](https://driverjs.com/docs/popover.md#event-handlers) |
| Draw everything yourself | `driver.js/headless`, on this page |
## The Pattern
Every headless UI is built from the same few hooks. Put your content in `data` on each step and render it when the step starts:
```js
import { driver } from "driver.js/headless";
const tour = driver({
steps: [{ element: "#save", advanceOn: "click", data: { text: "Save it" } }],
onHighlighted: (element, step, opts) => show(element, step.data, opts.index),
onDeselected: element => unmark(element),
onWaitingForElement: (element, step, opts) => showLoading(opts.signal),
onDestroyed: () => hide(),
});
tour.drive();
```
Your own buttons call `tour.moveNext()`, `tour.movePrevious()` and `tour.destroy()`. Steps with `advanceOn` move on by themselves when the user does the thing.
## Checklist Panel
The guide is a panel beside the app that ticks off steps as the user does them. Nothing covers the page, and the current target gets an outline from your own CSS class.
- `onHighlighted` adds a class to the element and redraws the panel. `opts.index` is the current step.
- `onDeselected` takes the class off again, also when the tour ends. If your framework re-renders the button, `onElementReplaced` puts the class on the new one.
- `opts.reason === "done"` in `onDestroyed` tells a finished tour from a closed one.
## Chat Assistant
Each step arrives as a chat message. Upload takes a moment, so the assistant shows that it's waiting until the Share button appears.
- `onHighlightStarted` posts the step's message as soon as its element is found.
- `waitForElement` holds the tour while the upload runs. `onWaitingForElement` shows "Uploading…", and its `signal` removes it when the wait ends.
- The same setup works for an AI assistant: put the step text in `data` and let your chat render it.
## Hand-Drawn Spotlight
Your own highlight: a dashed ring that glides between elements, with a sticky note and your own buttons and keys. No overlay and no popover from driver.js.
- `getBoundingClientRect()` on `tour.getActiveElement()` places the ring, so it stays on the element even after a re-render. A CSS transition on `translate`, `width` and `height` makes it glide.
- The note's buttons are built once and only their text changes, so keyboard focus stays on Next between steps.
- The headless build doesn't scroll or listen to keys, so the code does both: `scrollIntoView()`, then the arrow keys and Escape, skipped while the user types in a field.
- One `AbortController` removes every listener in `onDestroyed`.
## Hints Inside a Form
The guidance is part of the form: a line of help under the current field, and the tour moves on when the field is filled in correctly. Sign up unlocks at the end.
- `advanceOn` with `when` checks the field and moves on once it's right. The email waits for `change`, so the tour doesn't jump ahead mid-address. The password checks on every keystroke.
- `onHighlighted` moves one hint element into the current field and links it with `aria-describedby`, so screen readers read it too. Focus stays where the user put it.
- `:has(.inline-hint)` styles the current field with plain CSS.
**Uses**: [`driver.js/headless`](https://driverjs.com/docs/headless-tours.md), [`advanceOn`](https://driverjs.com/docs/action-driven-tours.md), [`waitForElement` and `onWaitingForElement`](https://driverjs.com/docs/configuration.md#missing-elements), [hooks](https://driverjs.com/docs/configuration.md#hooks), [navigation](https://driverjs.com/docs/api.md#navigation)
---
# Configuration
> Explore every Driver.js configuration option. Configure the driver globally, per step, or on the fly, with full TypeScript autocomplete and type safety.
Pass options to `driver()`. Options marked _step_ can also be set on a single step, where they override the driver's value.
```js
import { driver } from "driver.js";
import "driver.js/dist/driver.css";
const driverObj = driver({
showProgress: true,
overlayOpacity: 0.5,
steps: [
{
element: "#search",
popover: { title: "Search", description: "Find anything." },
},
{
element: "#export",
disableActiveInteraction: true,
popover: { title: "Export", side: "left" },
},
],
});
driverObj.drive();
```
Each `driver()` call is its own instance with its own configuration, steps and state. Only one instance is on screen at a time: starting one closes any other. To change options later, use [`setConfig()`](https://driverjs.com/docs/api.md#configuration).
All types on this page are exported from `driver.js`.
## Driver Configuration
```typescript
type Config = {
// The steps of the tour. Not needed for highlight().
steps?: DriveStep[];
// --- Overlay and highlight ---
// Animate between steps. (default: true)
animate?: boolean;
// Length of that animation and of the fade-in, in milliseconds.
// (default: 400)
duration?: number;
// Any CSS color. (default: "#000")
overlayColor?: string;
// (default: 0.7)
overlayOpacity?: number;
// Space between the element and the edge of the cutout, in pixels.
// (default: 10)
stagePadding?: number;
// Corner radius of the cutout, in pixels. (default: 5)
stageRadius?: number;
// Scroll smoothly to the highlighted element. (default: false)
smoothScroll?: boolean;
// Scroll the highlighted element and the popover into view. An object
// says where the element ends up, like { block: "start" }. See
// Scrolling and Focus. (default: true)
scrollIntoView?: boolean | ScrollIntoViewOpts;
// Let the page scroll while the tour is open. (default: true)
allowScroll?: boolean;
// --- Closing and navigation ---
// Let the user close the tour: with the close button, Escape or a click
// on the overlay. false also hides the close button. (default: true)
allowClose?: boolean;
// What a click on the overlay does. A function replaces the default and
// receives the same arguments as a hook. (default: "close")
overlayClickBehavior?: "close" | "nextStep" | "none" | DriverHook;
// Arrow keys move between steps and Escape closes. (default: true)
allowKeyboardControl?: boolean;
// Where the keyboard goes when a step shows: "popover", "element" (the
// first thing to use in the highlighted element) or "none" (it stays
// where it is). (default: "popover")
focus?: StepFocus;
// --- Interaction (all step) ---
// Block the highlighted element: true turns off all pointer events
// on it, "clicks" keeps hover and blocks clicks. (default: false)
disableActiveInteraction?: boolean | "clicks";
// Complete the step when this event happens on the highlighted element.
// (default: off)
advanceOn?: false | string | string[] | AdvanceOnEvent;
// Milliseconds to pause after advanceOn or advance() completes a step,
// before moving on. (default: 0)
advanceDelay?: number;
// Other elements the user may use during a step, like a menu it opens.
allowedElements?: AllowedElements;
// Called for every click during a step. Return false to block it.
onInteraction?: InteractionHook;
// Let the user use the whole page during a step, not only the
// highlighted element. (default: false)
allowPageInteraction?: boolean;
// Deprecated: use advanceOn: "click".
advanceOnClick?: boolean;
// --- Missing elements (all step) ---
// Milliseconds to wait for a step's element to appear. Infinity waits
// as long as it takes. (default: 0, no wait)
waitForElement?: number;
// Milliseconds a highlighted element that was removed gets to come back
// before onElementMissing runs. (default: waitForElement)
waitForRemovedElement?: number;
// Skip a step whose element is not on the page. (default: false)
skipMissingElement?: boolean;
// What to do when the highlighted element leaves the page for good, or a
// wait runs out. (default: "stay")
onElementMissing?: ElementMissing;
// Called when driver.js starts waiting for an element.
onWaitingForElement?: WaitingForElementHook;
// Called when the app re-renders the highlighted element and the step
// moves to the new one.
onElementReplaced?: DriverHook;
// --- Popover defaults (see Popover Configuration) ---
popoverClass?: string;
// Space between the popover and the cutout, in pixels. (default: 10)
popoverOffset?: number;
// (default: ["next", "previous", "close"] in a tour, [] in highlight())
showButtons?: ("next" | "previous" | "close")[];
disableButtons?: ("next" | "previous" | "close")[];
showProgress?: boolean;
progressText?: string;
nextBtnText?: string;
prevBtnText?: string;
doneBtnText?: string;
closeBtnLabel?: string;
// --- Hooks (see Hooks) ---
onPopoverRender?: (popover: PopoverDOM, opts: HookOpts) => void;
onPopoverPositioned?: (popover: PopoverDOM, opts: HookOpts) => void;
onHighlightStarted?: DriverHook;
onHighlighted?: DriverHook;
onDeselected?: DriverHook;
onDestroyStarted?: DriverHook;
onDestroyed?: DriverHook;
onNextClick?: DriverHook;
onPrevClick?: DriverHook;
onCloseClick?: DriverHook;
onDoneClick?: DriverHook;
};
```
## Step Configuration
A step is what you put in `steps` or pass to `highlight()`.
```typescript
type DriveStep = {
// What to highlight: a CSS selector (first match), an element, or a
// function returning one. Without it the popover is centered on the
// screen.
element?: string | Element | (() => Element);
// The popover of this step. See Popover Configuration.
popover?: Popover;
// Your own data, readable from the step in any hook.
data?: Record;
// Per-step versions of the driver options with the same name.
disableActiveInteraction?: boolean | "clicks";
allowPageInteraction?: boolean;
advanceOn?: false | string | string[] | AdvanceOnEvent;
advanceDelay?: number;
allowedElements?: AllowedElements;
onInteraction?: InteractionHook;
waitForElement?: number;
waitForRemovedElement?: number;
skipMissingElement?: boolean;
onElementMissing?: ElementMissing;
onWaitingForElement?: WaitingForElementHook;
onElementReplaced?: DriverHook;
scrollIntoView?: boolean | ScrollIntoViewOpts;
focus?: StepFocus;
advanceOnClick?: boolean;
// Per-step hooks. They run instead of the driver's.
onHighlightStarted?: DriverHook;
onHighlighted?: DriverHook;
onDeselected?: DriverHook;
};
```
If a step names an element that is not on the page, its popover is centered like a step without one, unless [`waitForElement` or `skipMissingElement`](#missing-elements) says otherwise.
## Popover Configuration
Set on a step's `popover`. The options that also exist on the driver fall back to the driver's value.
```typescript
type Popover = {
// HTML is allowed in both. Leave one out to show only the other.
title?: string;
description?: string;
// Side of the element the popover sits on. It flips when it doesn't fit.
// (default: "bottom")
side?: "top" | "right" | "bottom" | "left";
// Position along that side. (default: "start")
align?: "start" | "center" | "end";
// Buttons to show, and buttons to show but disable.
showButtons?: ("next" | "previous" | "close")[];
disableButtons?: ("next" | "previous" | "close")[];
// (defaults: "Next", "Previous", "Done")
nextBtnText?: string;
prevBtnText?: string;
// Text of the next button on the last step.
doneBtnText?: string;
// Screen reader label of the close button. (default: "Close")
closeBtnLabel?: string;
// Show the step count. (default: false)
showProgress?: boolean;
// {{current}} and {{total}} are replaced.
// (default: "{{current}} of {{total}}")
progressText?: string;
// Extra class on the popover, for styling.
popoverClass?: string;
// Makes the step an action step: the user has to do this to move on.
// HTML is allowed. See Action Steps below.
instruction?: string;
// Per-step hooks. They run instead of the driver's.
onPopoverRender?: (popover: PopoverDOM, opts: HookOpts) => void;
onPopoverPositioned?: (popover: PopoverDOM, opts: HookOpts) => void;
onNextClick?: DriverHook;
onPrevClick?: DriverHook;
onCloseClick?: DriverHook;
onDoneClick?: DriverHook;
};
```
Examples for position, buttons and custom buttons are in the [Popover guide](https://driverjs.com/docs/popover.md).
### Action Steps
An action step is a step with `popover.instruction`. The instruction shows in its own row, ending in a pulsing dot while the step waits, and the step only completes through `advanceOn`, [`advance()`](https://driverjs.com/docs/api.md#navigation) or `moveNext()`. The Next button, when `showButtons` has it, stays in its place but looks disabled (`aria-disabled`): pressing it, the right arrow key or the overlay shakes the popover instead of moving on, and `onNextClick` doesn't run. Previous, the close button and Escape work as usual. With `advanceDelay`, the dot becomes a check mark and the row and Next turn green for the pause; screen readers hear your `doneBtnText` ("Done") once. In `highlight()` the instruction is a plain line and nothing is gated.
```js
{
element: "#inbox",
advanceOn: "click",
popover: {
title: "Open your inbox",
instruction: "Click Inbox .",
},
}
```
In `highlight()`, `action` is only an instruction line. See [Action-Driven Tours](https://driverjs.com/docs/action-driven-tours.md) for live examples.
## Interaction
By default the user can use the highlighted element, and nothing else on the page. These options change that.
| You want to... | Use |
| --- | --- |
| Move on when the user clicks, types or picks something | `advanceOn: "click"`, `"input"`, `"change"`, ... |
| Move on only when the result is right | `advanceOn: { event, when }` |
| Accept one gesture on the element and block other clicks | `advanceOn: { event, strict: true }` |
| Take away the Next button so the user has to act | [`popover.instruction`](#action-steps) |
| Let the user use something outside the element, like a menu | `allowedElements` |
| Let the user use the whole page, like trying something out | `allowPageInteraction: true` |
| Let the user look but not touch | `disableActiveInteraction: true` |
| Keep hover and tooltips, block clicks | `disableActiveInteraction: "clicks"` |
| Decide per click, or react to a wrong click | `onInteraction` |
| Choose what a click on the dimmed page does | `overlayClickBehavior` |
### advanceOn
```typescript
type AdvanceOnEvent = {
event: string | string[];
when?: (
element: Element,
step: DriveStep,
opts: HookOpts & { event: Event }
) => boolean;
strict?: boolean;
};
```
- `event` is any DOM event name that reaches the highlighted element, or a list of them.
- `when` runs after your app has handled the event. The step completes only when it returns `true`.
- `strict: true` makes the element take only that gesture: other clicks, right-clicks and double-clicks on it are blocked and shake the popover. It applies when every event is a pointer gesture (`click`, `dblclick`, `contextmenu`, `auxclick`, pointer and mouse down and up).
- `false` on a step turns off the driver's `advanceOn` for it.
Completing a step runs `onNextClick` like the Next button does, or `onDoneClick` on the last step.
### onInteraction
```typescript
type InteractionHook = (
element: Element | undefined,
step: DriveStep,
opts: HookOpts & {
event: MouseEvent;
region: "element" | "allowed" | "outside";
}
) => false | void;
```
Called for every `click`, `auxclick`, `contextmenu` and `dblclick` during a step, before your app's handlers. `region` says where it happened: on the highlighted element, on one of the `allowedElements`, or anywhere else. Return `false` to block the event, including the `overlayClickBehavior` it would trigger. Clicks on the popover and key presses are not reported.
### allowedElements
```typescript
type AllowedElements =
| string
| Element
| Array
| (() => Element[] | NodeListOf | null | undefined);
```
Selectors, elements, or a function returning elements. They stay clickable, sit above the overlay and take part in Tab navigation. Selectors and functions are evaluated again as the page changes, so elements that appear later are included. If one still sits under the overlay, set `--driver-allowed-z-index` or target its positioned wrapper. When the highlighted element is inside an allowed element, like an item in an open menu, it gets the `driver-active-element-raised` class and a ring instead of the cutout; see [Theming](https://driverjs.com/docs/theming.md#css-variables).
### allowPageInteraction
With `allowPageInteraction: true` the page stays usable during the step: clicks go through the overlay, Tab moves through the whole page, and arrow keys and Escape typed into the page's own fields stay with the page. The highlighted element still follows `disableActiveInteraction` and a `strict` `advanceOn`, and `onInteraction` is still called. `overlayClickBehavior` doesn't apply, since clicks on the overlay reach the page. The [headless build](https://driverjs.com/docs/headless-tours.md) never blocks anything, so it doesn't need it.
### overlayClickBehavior
`"close"` ends the tour, `"nextStep"` moves on, `"none"` does nothing. On an [action step](#action-steps), `"close"` and `"nextStep"` shake the popover instead. `"nextStep"` does nothing while a step waits for its element. A function runs in every case.
### How Clicks Are Handled
While a tour runs, only the highlighted element, `allowedElements` and the popover take pointer events. A press anywhere else belongs to the tour, and your app never sees it:
- Its `pointerdown`, `mousedown`, `pointerup`, `mouseup`, `click`, `touchstart` and `touchend` are stopped on `window` in the capture phase. Only `window` capture listeners added before the tour started still run.
- Mouse events are also canceled, so focus stays where it was. Touch events are not, so scrolling works.
- A drag that starts in the highlighted element ends normally, wherever it is released.
The same goes for presses on an element with `disableActiveInteraction`, which also blocks the click that Enter or Space makes on it.
Only what the user does is stopped. Events your code dispatches, like `element.click()`, go through.
## Scrolling and Focus
When a step's element is not fully in view, driver.js scrolls it to the middle of the screen, or its top to the top of the screen when it is taller than the screen. `scrollIntoView` takes `block` and `inline` like the DOM's `scrollIntoView()` to put it somewhere else; what you leave out stays as it is. `false` turns scrolling off. A fixed header can be cleared with `scroll-margin-top` on the element.
```typescript
type ScrollIntoViewOpts = { block?: ScrollLogicalPosition; inline?: ScrollLogicalPosition };
driver({ scrollIntoView: { inline: "nearest" } }); // a wide table row keeps its first columns in view
```
The cutout and the popover follow the part of the element you can see: a row wider than the panel it scrolls in is only highlighted inside the panel, and the highlight moves as the panel scrolls.
`focus` decides where the keyboard goes when a step shows:
- `"popover"` (default): Next, or the popover itself.
- `"element"`: the first thing to use inside the highlighted element, like the field a step asks the user to fill in. It falls back to the popover when there is nothing to use there, or the element has `disableActiveInteraction: true`.
- `"none"`: it stays where it is. Use it with `allowPageInteraction`, so the user can keep typing where they were.
Either way, a screen reader still reads the popover out. When the tour ends, the keyboard goes back where it was before only if it is still on the popover.
## Missing Elements
| Situation | Option | What happens |
| --- | --- | --- |
| The next element renders late | `waitForElement: 3000` | The current step stays, with its popover in a waiting state, until the element appears or the time runs out |
| The element may not exist at all | `skipMissingElement: true` | The step is skipped in the direction of travel |
| The highlighted element is replaced | nothing, or `onElementReplaced` to hear about it | The step follows the new element matching its selector |
| The highlighted element is removed | `onElementMissing` | See below |
`onElementMissing` takes a preset or a function:
- `"stay"` (default): the step stays where the element was.
- `"previous"`: go back one step.
- `"previousAction"`: go back to the last [action step](#action-steps) whose element is still on the page, or one step back if there is none.
A removed element first gets `waitForRemovedElement` to come back, or `waitForElement` when that is not set. Set `waitForRemovedElement` when the two should differ, like waiting as long as it takes for an element to appear (`waitForElement: Infinity`) but going back soon after it is gone. A driver-level `waitForRemovedElement` applies to every step, including steps that set their own `waitForElement`. With `"stay"` there is no wait. `"previous"` and `"previousAction"` also keep the current step when the next step's `waitForElement` runs out, instead of showing that step without its element.
```typescript
type ElementMissing =
| "stay"
| "previous"
| "previousAction"
| ElementMissingHook;
type ElementMissingHook = (
element: Element | undefined,
step: DriveStep,
opts: HookOpts & { cause: "removed" | "timeout" }
) => false | void;
```
A function is called with `cause: "removed"` when the highlighted element is gone, and decides what to do. It is called with `cause: "timeout"` when a step's `waitForElement` runs out, with that step and its index; the step then shows without its element unless the function returns `false` or navigates.
`onWaitingForElement` is called when driver.js starts waiting for an element:
- A step's element hasn't appeared yet. `element` is `undefined`, and `opts.index` is that step's index. If another step is showing, it stays the current step until the element appears.
- The highlighted element was removed, and `onElementMissing` is not `"stay"`. `element` is the removed one, which gets `waitForRemovedElement` (or `waitForElement`) to come back. With `"stay"` there is no wait: the step stays, and `onElementReplaced` runs if a new element shows up.
`opts.signal` aborts when the wait ends: the element showed up, the time ran out or the tour moved on. It means "stop showing that you're waiting", not "found". `onHighlighted` or `onElementMissing` tells you how it ended.
```typescript
type WaitingForElementHook = (
element: Element | undefined,
step: DriveStep,
opts: HookOpts & { signal: AbortSignal }
) => void;
driver({
waitForElement: 3000,
onWaitingForElement: (element, step, opts) => {
showSpinner();
opts.signal.addEventListener("abort", hideSpinner);
},
});
```
`onElementReplaced` runs after the step has moved to the new element, so `getActiveElement()` already returns it. It doesn't run when the same element is put back.
Examples: [Wait for Elements](https://driverjs.com/docs/interactive-tours.md#wait-for-elements), [Optional Steps](https://driverjs.com/docs/interactive-tours.md#optional-steps), [menus](https://driverjs.com/docs/action-driven-tours.md#let-the-user-use-a-menu) and [slow loads](https://driverjs.com/docs/action-driven-tours.md#recover-from-a-slow-load).
## Hooks
```typescript
type DriverHook = (
element: Element | undefined,
step: DriveStep,
opts: HookOpts
) => void;
type HookOpts = {
config: Config;
state: State;
driver: Driver;
// Index of the active step. undefined in highlight().
index: number | undefined;
// Why the tour is ending. Only in the destroy hooks.
reason?: "done" | "close" | "escape" | "overlay" | "replaced" | "api";
// Aborts when the step is left. Only in onHighlightStarted and
// onHighlighted.
signal?: AbortSignal;
};
```
| Hook | Runs |
| --- | --- |
| `onHighlightStarted` | Before a step's element is highlighted |
| `onHighlighted` | Once the highlight has settled on the element |
| `onDeselected` | When a step is left, and when the tour ends |
| `onDestroyStarted` | When the user tries to end the tour. The tour only ends if you call `destroy()` |
| `onDestroyed` | After the tour has ended |
| `onPopoverRender` | When a step's popover is built, after it is added to the page and before it is positioned. Change its content here |
| `onPopoverPositioned` | Every time driver.js places the popover: when it shows, and again on scroll, resize, `refresh()` and `updatePopover()`. Move it here |
| `onNextClick`, `onPrevClick`, `onCloseClick` | Instead of the button's default action |
| `onDoneClick` | Instead of `onNextClick` on the last step |
- On the last step the order is: the step's `onDoneClick`, the driver's `onDoneClick`, the step's `onNextClick`, the driver's `onNextClick`. A driver-level `onDoneClick` therefore runs instead of a step's own `onNextClick` there.
- On an [action step](#action-steps), pressing the disabled Next, the right arrow key or the overlay doesn't run `onNextClick`; completing the step does.
- The click hooks replace the default. Call `moveNext()`, `movePrevious()` or `destroy()` yourself. `onNextClick` also runs for the right arrow key, `overlayClickBehavior: "nextStep"`, `advanceOn` and `advance()`.
- `index` is always the active step. Inside the `onDeselected` that runs between steps, that is the step being moved to.
- Content added in `onPopoverRender` stays for the whole step. A position set there is replaced the next time driver.js places the popover; set it in `onPopoverPositioned` instead, and it stays until the next placement. That hook can run once a frame while the page scrolls, so keep it quick.
- `signal` cleans up listeners for you: `window.addEventListener("saved", onSaved, { signal })`.
- `destroy()` does not run `onDestroyStarted`. Neither does a tour that is replaced by another instance.
### Why a Tour Ended
`onDestroyStarted`, `onDestroyed` and the `onDeselected` that runs on destroy get `opts.reason`:
| Reason | Meaning |
| --- | --- |
| `"done"` | Moved past the last step, including when the remaining steps were skipped |
| `"close"` | The close button |
| `"escape"` | The Escape key |
| `"overlay"` | A click on the overlay |
| `"replaced"` | Another driver instance started |
| `"api"` | Your code called `destroy()`, or `moveTo()` / `movePrevious()` outside the steps |
A `destroy()` you call from a hook keeps the reason of the user action that started it. See [Confirm Before Closing](https://driverjs.com/docs/confirm-before-closing.md) and [Track Tour Analytics](https://driverjs.com/docs/track-tour-analytics.md) for examples.
## State
`driverObj.getState()` returns the state, and hooks get it as `opts.state`.
```typescript
type State = {
// Whether a tour or highlight is showing.
isInitialized?: boolean;
// Index, element and step that are active. No index in highlight().
activeIndex?: number;
activeElement?: Element;
activeStep?: DriveStep;
// Element and step that were active before.
previousElement?: Element;
previousStep?: DriveStep;
// The popover's DOM elements.
popover?: PopoverDOM;
};
```
`PopoverDOM` is described in [Theming](https://driverjs.com/docs/theming.md#changing-the-popover-dom).
## Hints Configuration
Passed to `hints()` from `driver.js/hints`. See the [Hints guide](https://driverjs.com/docs/hints.md) for examples.
```typescript
type HintsConfig = {
hints?: DriverHint[];
// Beacon defaults for every hint. A hint's own values win.
beacon?: HintBeacon;
// Text of the dismiss button. (default: "Got it")
buttonText?: string;
// Same meaning as in tours.
popoverClass?: string;
popoverOffset?: number;
// Dim the page while a hint is open, with its element cut out.
// (default: false)
overlay?: boolean;
// (defaults: "#000" and 0.7)
overlayColor?: string;
overlayOpacity?: number;
// Called when a hint opens, and when it is dismissed.
onOpen?: HintHook;
onDismiss?: HintHook;
// Runs instead of dismissing when the button is clicked.
onButtonClick?: HintHook;
};
type HintHook = (
element: Element,
hint: DriverHint,
opts: { config: HintsConfig; hints: Hints }
) => void;
```
```typescript
type DriverHint = {
// A hint whose element is missing is skipped, and picked up on a
// later show().
element: string | Element | (() => Element);
// Used by open(), dismiss() and restore(), and to save dismissals.
// (default: the hint's index)
id?: string;
beacon?: HintBeacon;
popover?: {
title?: string;
description?: string;
side?: "top" | "right" | "bottom" | "left";
align?: "start" | "center" | "end";
popoverClass?: string;
// The dismiss button. (default: true)
showButton?: boolean;
buttonText?: string;
onButtonClick?: HintHook;
onPopoverRender?: (
popover: PopoverDOM,
opts: { hint: DriverHint; hints: Hints }
) => void;
};
// Run instead of the hooks in HintsConfig.
onOpen?: HintHook;
onDismiss?: HintHook;
data?: Record;
};
type HintBeacon = {
// Edge of the element the beacon sits on, and where along it.
// (defaults: "top" and "end")
side?: "top" | "right" | "bottom" | "left";
align?: "start" | "center" | "end";
// Move the beacon by this many pixels. Positive is right and down.
offsetX?: number;
offsetY?: number;
// Pulse. Off for users who prefer reduced motion. (default: true)
animate?: boolean;
className?: string;
};
```
## Checklist Configuration
Passed to `checklist()` from `driver.js/checklist`. See the [Checklists guide](https://driverjs.com/docs/checklists.md) for examples.
```typescript
type ChecklistConfig = {
// Identifies the checklist in events.
id: string;
items: ChecklistItem[];
// (defaults: "Get started", none, the title)
title?: string;
description?: string;
launcherText?: string;
// Shown instead once every item is done.
completeTitle?: string;
completeDescription?: string;
completeLauncherText?: string;
// {{done}}, {{total}}, {{remaining}} and {{percent}} are replaced.
// (default: "{{done}} of {{total}}")
progressText?: string;
// The count on the launcher. "" hides it.
// (default: "{{done}}/{{total}}")
launcherProgressText?: string;
// false hides the launcher. Open the panel yourself with open() or
// toggle().
// (default: true)
launcher?: boolean;
// (default: "bottom-right")
position?: "bottom-right" | "bottom-left" | "top-right" | "top-left";
// Distance from the screen edges, in pixels. (default: 20, 12 on phones)
offset?: { x?: number; y?: number };
className?: string;
// Let users tick and untick items with the check circle.
// (default: false)
allowManualComplete?: boolean;
// Ids of the items that are already done.
completed?: string[];
// Called on every change.
onProgress?: (progress: {
completed: string[];
done: number;
total: number;
}) => void;
// Called when an item is ticked, and once when all are.
onItemComplete?: (
item: ChecklistItem,
opts: { checklist: Checklist }
) => void;
onComplete?: (opts: { checklist: Checklist }) => void;
// Called with every event. See the Checklists guide for the types.
onEvent?: (event: ChecklistEvent) => void;
};
```
```typescript
type ChecklistItem = {
// Saved progress is a list of these, so keep them stable.
id: string;
// HTML is allowed in both.
title: string;
description?: string;
// What a click does. A tour ticks the item when the user finishes it,
// a link or an action ticks it on click.
tour?: DriveStep[] | Config | Driver;
href?: string;
action?: (item: ChecklistItem, opts: { checklist: Checklist }) => void;
// Ticks the item once it returns true, instead of the rules above.
completeWhen?: () => boolean;
// Overrides the checklist's allowManualComplete.
allowManualComplete?: boolean;
data?: Record;
};
```
---
# API Reference
> Complete Driver.js API reference: every method available on the driver, hints and checklist instances, with examples.
`driver()` returns an object with the methods below. The options it takes are in [Configuration](https://driverjs.com/docs/configuration.md).
```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](https://driverjs.com/docs/configuration.md#why-a-tour-ended) `"api"`, or the reason of the user action when you call it from a hook.
## Navigation
```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`](https://driverjs.com/docs/configuration.md#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 Save .",
},
}
```
`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`](https://driverjs.com/docs/configuration.md#missing-elements) 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](https://driverjs.com/docs/configuration.md#action-steps), 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 Inbox .");
// 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](https://driverjs.com/docs/configuration.md#hints-configuration), examples in the [Hints guide](https://driverjs.com/docs/hints.md).
```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](https://driverjs.com/docs/configuration.md#checklist-configuration), examples in the [Checklists guide](https://driverjs.com/docs/checklists.md).
```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
```
---
# Theming
> Theme Driver.js to match your brand. Apply custom classes and CSS to the popover, buttons, overlay, hints and checklists, or restyle the driver from the ground up.
Driver.js is styled with plain CSS. Override its classes, set its CSS variables, or change the popover's DOM in a hook.
## Popover
Give the popover your own class with `popoverClass`, then style it. Set it on the driver for every popover, or on a step's `popover` for one.
```js
import { driver } from "driver.js";
import "driver.js/dist/driver.css";
const driverObj = driver({
popoverClass: "driverjs-theme",
steps: [
// ...
],
});
driverObj.drive();
```
```css
.driver-popover.driverjs-theme {
background-color: #fde047;
color: #000;
}
.driver-popover.driverjs-theme .driver-popover-title {
font-size: 20px;
}
.driver-popover.driverjs-theme .driver-popover-title,
.driver-popover.driverjs-theme .driver-popover-description,
.driver-popover.driverjs-theme .driver-popover-progress-text {
color: #000;
}
.driver-popover.driverjs-theme button:not(.driver-popover-close-btn) {
flex: 1;
text-align: center;
background-color: #000;
color: #fff;
border: 2px solid #000;
text-shadow: none;
font-size: 14px;
padding: 5px 8px;
border-radius: 6px;
}
.driver-popover.driverjs-theme .driver-popover-navigation-btns {
justify-content: space-between;
gap: 3px;
}
.driver-popover.driverjs-theme .driver-popover-close-btn {
color: #9b9b9b;
}
.driver-popover.driverjs-theme .driver-popover-close-btn:hover {
color: #000;
}
/* The arrow is a border, one rule per side */
.driver-popover.driverjs-theme .driver-popover-arrow-side-left {
border-left-color: #fde047;
}
.driver-popover.driverjs-theme .driver-popover-arrow-side-right {
border-right-color: #fde047;
}
.driver-popover.driverjs-theme .driver-popover-arrow-side-top {
border-top-color: #fde047;
}
.driver-popover.driverjs-theme .driver-popover-arrow-side-bottom {
border-bottom-color: #fde047;
}
```
### Popover Classes
```css
.driver-popover {} /* The popover */
.driver-popover-arrow {} /* The arrow pointing at the element */
.driver-popover-arrow-side-top {} /* Named after the popover's side */
.driver-popover-arrow-none {} /* Hidden: popover centered or over */
.driver-popover-title {}
.driver-popover-description {}
.driver-popover-close-btn {} /* The close button, top right */
.driver-popover-footer {} /* Progress text and buttons */
.driver-popover-progress-text {}
.driver-popover-navigation-btns {} /* Holds the buttons */
.driver-popover-footer-btn {} /* Button look. Add it to yours too */
.driver-popover-prev-btn {}
.driver-popover-next-btn {}
.driver-popover-done-btn {} /* Next, on the last step */
.driver-popover-btn-disabled {} /* On a disabled button */
/* Where the popover ended up, after flipping to fit the screen */
.driver-popover-side-top {} /* or -right, -bottom, -left */
.driver-popover-align-start {} /* or -center, -end */
/* Action steps */
.driver-popover-has-instruction {} /* On the popover of an action step */
.driver-popover-instruction {} /* The instruction row */
.driver-popover-instruction-text {} /* Its text */
/* The dot at its end; a check mark once done */
.driver-popover-instruction-indicator {}
/* On the popover while it pauses for advanceDelay */
.driver-popover-instruction-done {}
/* Next, while the step waits for the user */
.driver-popover-btn-disabled[aria-disabled] {}
.driver-popover-feedback {} /* The line shown by nudge("...") */
/* States */
.driver-popover-waiting {} /* While it waits for an element */
.driver-popover-nudge {} /* While nudge() shakes it */
```
The popover also has the id `driver-popover-content`, which the highlighted element's `aria-controls` points to.
Animations use these keyframes, so you can swap one by setting `animation` on the class that runs it: `driver-nudge-shake` on `.driver-popover-nudge`, `driver-nudge-flash` in its place with reduced motion, and `driver-instruction-pulse` on `.driver-popover-instruction-indicator`.
### CSS Variables
Set them on `:root`, or on your `popoverClass` to scope them.
```css
:root {
/* Font of the popover, and of checklists */
--driver-popover-font-family: "Inter", sans-serif;
/* Action steps: the instruction row */
--driver-instruction-background: #f2f2f2;
--driver-instruction-color: inherit;
--driver-instruction-padding: 8px 10px;
--driver-instruction-radius: 4px;
/* Action steps: the dot at the end of the row, and the disabled Next */
--driver-instruction-indicator-color: #f59e0b;
--driver-instruction-indicator-size: 8px;
--driver-instruction-next-color: #a3a3a3;
/* Action steps: the done state, for the row, the check mark and Next */
--driver-instruction-done-background: #dcfce7;
--driver-instruction-done-color: #15803d;
/* The line shown by nudge("...") */
--driver-feedback-color: #b45309;
/* The shake of nudge(), and the flash shown with reduced motion */
--driver-nudge-distance: 6px;
--driver-nudge-duration: 500ms;
--driver-nudge-color: #f59e0b;
/* Read-only: set from the duration option while a tour runs, for
your own transitions to match */
--driver-animation-duration: 400ms;
/* Stacking of allowedElements above the overlay */
--driver-allowed-z-index: 10001;
/* The highlighted element inside an allowed element, like an item in an
open menu: a ring and a tint instead of the cutout */
--driver-raised-highlight-color: #2563eb;
--driver-raised-highlight-width: 2px;
--driver-raised-highlight-offset: -2px;
--driver-raised-highlight-background: rgb(37 99 235 / 0.1);
}
```
The values above are the defaults, except the font. Its default is:
```css
"Helvetica Neue", Inter, ui-sans-serif, "Apple Color Emoji", Helvetica,
Arial, sans-serif;
```
### Action Steps
An [action step](https://driverjs.com/docs/action-driven-tours.md#make-the-user-act) shows an instruction row that ends in a pulsing dot, and a Next button that looks disabled until the user has done it. While the step pauses for `advanceDelay` the dot becomes a check mark and the row and Next turn green. The dot and the check are drawn in CSS, don't animate with `prefers-reduced-motion`, and are hidden from screen readers. The variables cover the colors and sizes, and the classes the rest.
```js
const driverObj = driver({
popoverClass: "my-theme",
showButtons: ["next", "close"],
steps: [
{
element: "#publish",
advanceOn: "click",
advanceDelay: 1200,
popover: {
title: "Publish the page",
instruction: "Click Publish .",
},
},
// ...
],
});
driverObj.drive();
```
```css
.my-theme {
--driver-instruction-background: #eef2ff;
--driver-instruction-color: #3730a3;
--driver-instruction-radius: 999px;
--driver-instruction-padding: 8px 14px;
--driver-instruction-indicator-color: #6366f1;
--driver-instruction-indicator-size: 10px;
--driver-instruction-done-background: #dcfce7;
--driver-instruction-done-color: #166534;
}
.my-theme.driver-popover-instruction-done .driver-popover-instruction {
font-weight: 600;
}
```
To drop the dot and the check, hide the indicator. To change the row altogether, replace the content of `popover.instruction` in [`onPopoverRender`](#changing-the-popover-dom); driver.js leaves it alone from then on. `popover.instructionIndicator` is the dot itself.
```css
.driver-popover-instruction-indicator {
display: none;
}
```
### Changing the Popover DOM
`onPopoverRender` gets the popover's elements before it shows. Add, move or change anything. See [Custom Buttons](https://driverjs.com/docs/custom-buttons.md) for a live example.
```typescript
type PopoverDOM = {
wrapper: HTMLElement;
arrow: HTMLElement;
title: HTMLElement;
description: HTMLElement;
footer: HTMLElement;
progress: HTMLElement;
previousButton: HTMLButtonElement;
nextButton: HTMLButtonElement;
closeButton: HTMLButtonElement;
footerButtons: HTMLElement;
// Only on steps with popover.instruction: the row, and the indicator at
// its end.
instruction?: HTMLElement;
instructionIndicator?: HTMLElement;
// Only after nudge("...") showed a message
feedback?: HTMLElement;
};
```
```js
const driverObj = driver({
onPopoverRender: popover => {
const link = document.createElement("a");
link.href = "/help/tours";
link.textContent = "Learn more";
popover.description.append(" ", link);
},
});
```
## Overlay
`overlayColor` takes any CSS color and `overlayOpacity` a number from 0 to 1. The defaults are `"#000"` and `0.7`.
```js
const driverObj = driver({
overlayColor: "red",
overlayOpacity: 0.3,
});
driverObj.highlight({
popover: { title: "A red overlay", description: "Any CSS color works." },
});
```
`stagePadding` and `stageRadius` set the size and corner radius of the cutout around the element.
## Page and Element Classes
```css
/* On while a tour or highlight is showing */
.driver-active {}
.driver-fade {} /* With animate: true */
.driver-simple {} /* With animate: false */
.driver-no-scroll {} /* With allowScroll: false */
.driver-overlay {} /* The overlay, an */
.driver-active-element {} /* The highlighted element */
.driver-allowed-element {} /* Each of the allowedElements */
.driver-active-element-raised {} /* ...inside an allowed element */
.driver-no-interaction {} /* With disableActiveInteraction: true */
/* The highlighted element's parent, and if it scrolls, -no-scroll too,
which stops it scrolling during the step */
.driver-active-element-parent {}
.driver-active-element-parent-no-scroll {}
```
Classes not listed on this page, like the ones driver.js uses to position layers or announce steps to screen readers, are internal and may change.
## Hints
Hint popovers are regular popovers with an extra `driver-hint-popover` class, so everything above applies. The beacons read these variables, set on `.driver-hint` or on a class you pass as `beacon.className`. The values are the defaults:
```css
.driver-hint {
--driver-hint-size: 24px;
--driver-hint-color: #818cf8;
--driver-hint-animation-duration: 2s; /* One pulse */
}
```
```css
.driver-hint {} /* The beacon, a */
.driver-hint-dot {} /* Its dot */
.driver-hint-pulse {} /* The pulsing ring (driver-hint-pulse) */
.driver-hint-hidden {} /* While its element is scrolled out of view */
.driver-hint-popover {} /* On the popover, next to .driver-popover */
.driver-hint-overlay {} /* The dimmed page, with overlay: true */
```
See [Styling Hints](https://driverjs.com/docs/hints.md#styling) for live examples.
## Checklist
[Checklists](https://driverjs.com/docs/checklists.md) have their own stylesheet and classes.
### Accent Color
`--driver-checklist-color` colors the progress bar, the ticks and the focus rings.
```css
:root {
--driver-checklist-color: #16a34a;
}
```
### Custom Theme
Pass `className` to put your own class on the widget, then style its parts. This is the theme of the driver.js homepage:
```js
checklist({
id: "onboarding",
className: "checklist-brutalist",
items,
});
```
Its CSS, and more themes to copy, are on the [Checklist Themes](https://driverjs.com/docs/checklist-themes.md) page.
### Checklist Classes
```css
.driver-checklist {} /* The widget, in a corner */
.driver-checklist-bottom-right {} /* or -bottom-left, -top-right… */
.driver-checklist-no-launcher {} /* With launcher: false */
.driver-checklist-complete {} /* Added once every item is done */
.driver-checklist-launcher {} /* The button that opens the panel */
.driver-checklist-launcher-text {}
.driver-checklist-launcher-count {} /* "1/4" */
.driver-checklist-panel {}
.driver-checklist-header {}
.driver-checklist-title {}
.driver-checklist-description {}
.driver-checklist-close-btn {}
.driver-checklist-progress {}
.driver-checklist-progress-bar {}
.driver-checklist-progress-fill {}
.driver-checklist-progress-text {} /* "1 of 4" */
.driver-checklist-items {}
.driver-checklist-item {}
.driver-checklist-item-done {} /* Once the item is done */
.driver-checklist-check {} /* The circle */
.driver-checklist-item-trigger {} /* Its link, button or row */
.driver-checklist-item-title {}
.driver-checklist-item-description {}
```
The widget also reads these variables:
```css
.driver-checklist {
/* Distance from the screen edges. Defaults: 20px, 12px on phones */
--driver-checklist-offset-x: 20px;
--driver-checklist-offset-y: 20px;
}
```
The `offset` option sets them for you. The panel opens with the `driver-checklist-in` keyframes, or `driver-checklist-in-down` at the top corners.
It sets `--driver-checklist-progress` to the progress as a percentage, for progress drawn in CSS like the [progress ring](https://driverjs.com/docs/checklist-themes.md#progress-ring). The font follows `--driver-popover-font-family`.
---
# Migrate to 1.x
> Upgrade from Driver.js 0.x to 1.x with this step-by-step migration guide covering the new API, imports, and architecture changes in the 1.0 rewrite.
Driver.js 1.x has a new API. This page lists what changed since 0.x. The current options are in [Configuration](https://driverjs.com/docs/configuration.md), the methods in the [API Reference](https://driverjs.com/docs/api.md).
## Import
```diff
- import Driver from 'driver.js';
- import 'driver.js/dist/driver.min.css';
+ import { driver } from "driver.js";
+ import "driver.js/dist/driver.css";
```
## Initialization
```diff
- const driverObj = new Driver(config);
- driverObj.defineSteps(steps);
+ const driverObj = driver({ ...config, steps });
```
## Configuration
```diff
const config = {
- overlayClickNext: false,
+ overlayClickBehavior: "close", // or "nextStep", "none", a function
- closeBtnText: 'Close', // Removed: the close button is an icon
- scrollIntoViewOptions: {}, // Removed: see smoothScroll
- opacity: 0.75,
+ overlayOpacity: 0.75,
- className: 'scoped-class',
+ popoverClass: 'scoped-class',
- padding: 10,
+ stagePadding: 10,
- showButtons: false,
+ showButtons: ["next", "previous", "close"], // [] for none
- keyboardControl: true,
+ allowKeyboardControl: true,
- onHighlightStarted: (Element) => {},
- onHighlighted: (Element) => {},
- onDeselected: (Element) => {},
+ // Every hook now gets (element, step, { config, state, driver, index })
+ onHighlightStarted: (element, step, opts) => {},
+ onHighlighted: (element, step, opts) => {},
+ onDeselected: (element, step, opts) => {},
- onReset: (Element) => {},
+ onDestroyStarted: (element, step, opts) => {},
+ onDestroyed: (element, step, opts) => {},
+ onCloseClick: (element, step, opts) => {},
- onNext: (Element) => {},
- onPrevious: (Element) => {},
+ // These replace the default: call moveNext() / movePrevious() yourself
+ onNextClick: (element, step, opts) => {},
+ onPrevClick: (element, step, opts) => {},
+ // New
+ overlayColor: "#000",
+ stageRadius: 5,
+ popoverOffset: 10,
+ disableButtons: ["previous"],
+ showProgress: true,
+ progressText: "{{current}} of {{total}}",
+ onPopoverRender: (popover, opts) => {},
}
```
## Steps and Popovers
```diff
const step = {
- element: '.some-element', // Required
+ element: '.some-element', // Optional: centered without it
popover: {
- closeBtnText: 'Close', // Removed
- className: 'popover-class',
+ popoverClass: 'popover-class',
- showButtons: false,
+ showButtons: ["next", "previous", "close"],
- title: '', // Required
- description: '', // Required
+ title: '', // Optional
+ description: '', // Optional
- // left, left-center, left-bottom, top, top-center, top-right,
- // right, right-center, right-bottom, bottom, bottom-center,
- // bottom-right, mid-center
- position: 'left',
+ side: "left", // "top" | "right" | "bottom" | "left"
+ align: "start", // "start" | "center" | "end"
+ // New
+ showProgress: true,
+ progressText: "{{current}} of {{total}}",
+ onPopoverRender: (popover, opts) => {},
+ onNextClick: (element, step, opts) => {},
+ onPrevClick: (element, step, opts) => {},
+ onCloseClick: (element, step, opts) => {},
},
+ // New: per-step hooks
+ onHighlightStarted: (element, step, opts) => {},
+ onHighlighted: (element, step, opts) => {},
+ onDeselected: (element, step, opts) => {},
};
```
## Methods
```diff
- driverObj.preventMove(); // Removed: use onNextClick + moveNext()
- activeElement.getCalculatedPosition();
- activeElement.hidePopover();
- activeElement.showPopover();
- activeElement.getNode();
- const isActivated = driverObj.isActivated;
+ const isActivated = driverObj.isActive();
- driverObj.start(stepNumber);
+ driverObj.drive(stepNumber);
- driverObj.highlight(string | stepDefinition);
+ driverObj.highlight(stepDefinition);
- driverObj.reset();
+ driverObj.destroy();
- driverObj.hasHighlightedElement();
+ driverObj.getActiveElement() !== undefined;
- driverObj.getHighlightedElement();
+ driverObj.getActiveElement();
- driverObj.getLastHighlightedElement();
+ driverObj.getPreviousElement();
+ // New
+ driverObj.moveTo(stepIndex);
+ driverObj.getActiveStep();
+ driverObj.getPreviousStep();
+ driverObj.isLastStep();
+ driverObj.isFirstStep();
+ driverObj.getState();
+ driverObj.getConfig();
+ driverObj.setConfig(config);
+ driverObj.refresh();
```