docs-src/src/content/docs/guides/usage.md
The latest versions of Rollup and Webpack support ES6 imports. Shepherd ships as an ES module which should allow you to import using standard ES import syntax.
i.e.
import Shepherd from 'shepherd.js';
First create a new Tour instance for your tour:
const tour = new Shepherd.Tour({
useModalOverlay: true,
defaultStepOptions: {
classes: 'shadow-md bg-purple-dark',
scrollTo: true
}
});
The defaultStepOptions option allows you to specify any options which should
be applied to all this tour's steps by default.
Next, add your steps:
tour.addStep({
id: 'example-step',
text: 'This step is attached to the bottom of the <code>.example-css-selector</code> element.',
attachTo: {
element: '.example-css-selector',
on: 'bottom'
},
classes: 'example-step-extra-class',
buttons: [
{
text: 'Next',
action: tour.next
}
]
});
Finally, to start the tour, just call start on your Tour instance:
tour.start();
If you need to remove a step from your tour, call removeStep on your Tour
instance. If the step currently being displayed is the one you're removing, and
there are steps left in the tour, then the first one will be shown, otherwise,
the tour will be cancelled.
tour.removeStep('example-step');
Shepherd exposes a single object onto the window, Shepherd.
That global object fires several events to let you link up actions with events occurring in any tour:
Shepherd.on(eventName, handler, [context]): Bind an eventShepherd.off(eventName, [handler]): Unbind an eventShepherd.once(eventName, handler, [context]): Bind just the next instance of
an eventThe global Shepherd fires the following events whenever a Tour instance fires
them. It adds to the object passed to the event handlers a tour key pointing
to the instance which fired the event:
completecancelhideshowstartactiveinactiveFor multiple events, you can use something like:
['complete', 'cancel'].forEach((event) =>
shepherd.on(event, () => {
// some code here
})
);
The global Shepherd includes a property which is always set to the currently
active tour, or null if there is no active tour:
Shepherd.activeTourYou create a Tour object for each tour you'd like to create.
Tour's constructor accepts a hash of options:
const myTour = new Shepherd.Tour(options);
classPrefix: The prefix to add to the shepherd-enabled and
shepherd-target class names Shepherd puts on the target element, as well
as to the data-shepherd-step-id attribute. Nothing else is prefixed: the
popup keeps its own unprefixed shepherd-enabled class, and
shepherd-target-click-disabled stays unprefixed too, because the shipped
stylesheet keys click blocking on it and cannot know your runtime prefix.confirmCancel:
window.confirm before cancellingconfirmCancelMessage: The message to display in the confirm dialogdefaultStepOptions: Default options for Steps created through addStepexitOnEsc: Exiting the tour with the escape key will be enabled unless this
is explicitly set to false.keyboardNavigation: Navigating the tour via left and right arrow keys will
be enabled unless this is explicitly set to false.stepsContainer An optional container element for the steps. If not set, the
steps will be appended to document.body.modalContainer An optional container element for the modal. If not set, the
modal will be appended to document.body.steps: An array of step options objects or Step instances to initialize the
tour with.tourName: An optional "name" for the tour. This will be appended to the the
tour's dynamically generated id property.useModalOverlay: Whether or not steps should be placed above a darkened
modal overlay. If true, the overlay will create an opening around the target
element so that it can remain interactive.addStep(options): Creates a new Step object with options, and returns the
Step instance it created. If the options hash doesn't include an id, one
will be generated. You can also pass an existing Step instance rather than
options, but note that Shepherd does not support a Step being attached to
multiple Tours.addSteps([Steps]): Add multiple steps to the tourgetById(id): Return a step with a specific idisActive(): Check if the tour is activenext(): Advance to the next step, in the order they were addedback(): Show the previous step, in the order they were addedcancel(): Trigger cancel on the current step, hiding it without advancingcomplete(): Calls _done() triggering the complete eventhide(): Hide the current stepshow([id]): Show the step specified by id (if it's a string), or index (if
it's a number) provided. Defaults to the first step.start(): Show the first step and begin the tourgetCurrentStep(): Returns the currently shown stepremoveStep(id): Removes the step from the touron(eventName, handler, [context]): Bind an eventoff(eventName, [handler]): Unbind an eventonce(eventName, handler, [context]): Bind just the next instance of an eventstart() always returns a promise, and show(), next(), and back() return
one while a step is waiting on its attachTo.element (see waitForElement
below). Await them if you need to know the step is on screen β otherwise they
can be called and ignored, as before.
complete: Triggered when the last step is advancedcancelhideshow: Triggered with a hash of the step and the previous stepstartSteps are instances of the Step object. They are generally created by the
Tour::addStep method, which returns the Step instance it created.
text: The text in the body of the step. It can be one of three types:
HTMLElement objectFunction to be executed when the step is built. It must return one the two
options above.title: The step's title. It becomes an h3 at the top of the step.label: An aria-label for the step's dialog element. Use it to give a step
an accessible name when it has no visible title β a step with neither gets
no naming attribute at all, so its dialog has no accessible name and screen
readers announce it without one. It can also be a function that returns a
string (useful with i18n solutions). It is ignored when title is set,
because the title already supplies the accessible name via aria-labelledby;
a function-valued label is not invoked in that case. An empty or
whitespace-only value omits the attribute. It can be set on
defaultStepOptions, but prefer a distinct label per step so each dialog
has a meaningful, unique name.attachTo: The element the step should be attached to on the page. An object
with properties element and on.
element: An element selector string, a DOM element, or a function
(returning a selector, a DOM element, null or undefined).on: The optional direction to place the Floating UI tooltip relative to
the element.
const new Step(tour, {
attachTo: { element: '.some .selector-path', on: 'left' },
...moreOptions
});
If you donβt specify an attachTo the element will appear in the middle of the
screen. The same will happen if your attachTo.element callback returns null,
undefined, or a selector that does not exist in the DOM. The waitForElement
and skipMissingElement options described below let you change this behavior
for elements that are missing or rendered late.
If you omit the on portion of attachTo, the element will still be
highlighted, but the tooltip will appear in the middle of the screen, without an
arrow pointing to the target.
If the element to highlight does not yet exist while instantiating tour steps,
you may use lazy evaluation by supplying a function to attachTo.element. The
function will be called in the before-show phase.
beforeShowPromise: A function that returns a promise. When the promise
resolves, the rest of the show code for the step will execute. For example:
beforeShowPromise: function() {
return new Promise(function(resolve) {
$('#my-bootstrap-modal').on('shown.bs.modal', function () {
resolve();
});
});
},
canClickTarget A boolean, that when set to false, will set
pointer-events: none on the target. The blocking is delivered by
shepherd.css, so it has no effect if you have opted out of Shepherd's
stylesheet without providing an equivalent rule.
cancelIcon Options for the cancel icon
attrs Additional HTML attributes to apply to the cancel icon button
element. This is useful for adding data attributes for testing or analytics.
Note: These attributes cannot override critical properties like type,
onclick, class, or aria-label.cancelIcon: {
enabled: true,
label: 'Close Tour',
attrs: {
'data-test': 'close-tour-button',
'data-analytics-id': 'tour-close'
}
}
enabled Should a cancel "β" be shown in the header of the step?label The label to add for aria-labelclasses: A string of extra classes to add to the step's content element.
data: Arbitrary, JSON-serializable data to associate with the step. Shepherd
does not use it internally; read it back from step.options.data in your
event handlers and button actions. Useful for analytics ids or other metadata,
e.g. on generated tour definitions.
buttons: An array of buttons to add to the step. These will be rendered in a
footer below the main body text. Each button in the array is an object of the
format:
attrs: Additional HTML attributes to apply to the button element. Useful
for adding data attributes for testing or analytics.label: The label to add for aria-label. It can also be a function that
returns a string (useful with i18n solutions).disabled: A boolean that controls the disabled attribute. It can also be
a function that returns a boolean.classes: Extra classes to apply to the <a>secondary: A boolean, that when true, adds a shepherd-button-secondary
class to the buttontext: The HTML text of the button. It can also be a function that returns
a string (useful with i18n solutions).action: A function executed when the button is clicked on. It is
automatically bound to the tour the step is associated with, so things
like this.next will work inside the action. You can use action to skip
steps or navigate to specific steps, with something like: action() {
return this.show('some_step_name');
}
extraHighlights: An array of extra element selectors to highlight when the
overlay is shown The tooltip wonβt be fixed to these elements, but they will
be highlighted just like the attachTo element. They do not have to share a
scroll container with the attachTo element: each one is clipped vertically by
the scroll containers that actually crop it, so only the part of it that is
scrolled into view is cut out of the overlay. An element positioned outside
those containers β fixed, or absolute against a containing block above
them β is cut out in full, matching where it is painted.
advanceOn: An action on the page which should advance shepherd to the next
step. It should be an object with a string selector and an event name. For
example: {selector: '.some-element', event: 'click'}. It doesn't have to be
an event inside the tour, it can be any event fired on any element on the
page. You can also always manually advance the Tour by calling
myTour.next().
highlightClass: An extra class to apply to the attachTo element when it is
highlighted (that is, when its step is active). You can then target that
selector in your CSS.
id: The string to use as the id for the step. If an id is not passed one
will be generated.
modalOverlayOpeningPadding: An amount of padding to add around the modal
overlay opening
modalOverlayOpeningRadius: An amount of border radius to add around the
modal overlay opening. It can be either a number or an object with properties
{ topLeft, bottomLeft, bottomRight, topRight }
floatingUIOptions: Extra options to pass to
Floating UI. This includes
strategy, which sets the CSS position of the step element and defaults to
'absolute'. It can be set per-step or on defaultStepOptions. See
Floating UI's strategy documentation
for when 'fixed' is the better choice. Note that steps without an attachTo
element are always centered with position: fixed and ignore strategy.
showOn: A function that, when it returns true, will show the step. If it
returns false, the step will be skipped.
skipMissingElement: A boolean. When true, a step whose attachTo.element
cannot be found in the DOM is skipped (like showOn returning false) instead
of being shown centered. If all remaining steps are skipped, the tour
completes going forward, or cancels going backward. It can also be set on
defaultStepOptions to apply to every step. Steps without an attachTo
element are never skipped, since they are intentionally centered.
waitForElement: The maximum amount of time, in milliseconds, to wait for the
attachTo.element to appear in the DOM before showing the step. The DOM is
watched with a MutationObserver, falling back to polling where
MutationObserver is unavailable, so the step attaches as soon as the element
appears. If the timeout expires, the step falls back to its default behavior:
skipped when skipMissingElement is true, otherwise shown centered. It can
also be set on defaultStepOptions to apply to every step. Useful for targets
that are rendered asynchronously.
Both options look the target up before the step's own beforeShowPromise and
before-show handlers run, so they cannot see an element that those handlers
create β keep using beforeShowPromise for targets the step itself renders.
Both are plain JSON values, so a tour definition using them stays
serializable.
scrollTo: Should the element be scrolled to when this step is shown? If
true, uses the default scrollIntoView, if an object, passes that object as
the params to scrollIntoView i.e. {behavior: 'smooth', block: 'center'}
scrollToHandler: A function that lets you override the default scrollTo
behavior and define a custom action to do the scrolling, and possibly other
logic.
when: You can define show, hide, etc events inside when. For example:
when: {
show: function() {
window.scrollTo(0, 0);
}
}
show(): Show this stephide(): Hide this step. The step's element stays in the DOM, so the step can
be shown again later.cancel(): Hide this step and trigger the cancel eventcomplete(): Hide this step and trigger the complete eventscrollTo(): Scroll to this step's elementisOpen(): Returns true if the step is currently showndestroy(): Permanently tear the step down β removes its element from the
DOM, destroys the Floating UI instance, and triggers the destroy eventupdateStepOptions(options): Merge new options into the step and re-render
its element in placegetElement(): Returns the step's element β undefined if the step has never
been shown, null if it has been destroyedgetTarget(): Returns the step's resolved attachTo elementon(eventName, handler, [context]): Bind an eventoff(eventName, [handler]): Unbind an eventonce(eventName, handler, [context]): Bind just the next instance of an eventbefore-show: Triggered at the start of every show(), before the step's
element is createdshow: Triggered at the end of every show(), once the element is in the DOM
and positionedbefore-hide: Triggered at the start of every hide()hide: Triggered at the end of every hide()complete: Triggered by step.complete()cancel: Triggered by step.cancel()destroy: Triggered when the step is disposed of for good β by
step.destroy(), by tour.removeStep(id), or for every step in the tour when
the tour completes or is cancelledPlease note that complete and cancel are only ever triggered if you call the
associated methods in your code.
| What happens | Events, in order |
|---|---|
| A step is shown for the first time | before-show, show |
Advancing away with next(), back(), show(id) | before-hide, hide |
| The same step is shown again later | before-show, show |
tour.removeStep(id) on the step that is open | before-hide, hide, destroy |
tour.complete() or tour.cancel() | destroy, once for every step |
Shepherd rebuilds a step's element from scratch on every show(), but that is
an implementation detail β recreating the element does not emit destroy.
The event fires only when the step is actually being thrown away, so use it to
release anything you allocated for the step, and before-hide / hide for work
that should run every time the step goes away.
destroy() is not guarded against running more than once, so calling it
yourself and then completing the tour will emit destroy twice. Keep your
teardown idempotent if you do both.
Behavior change β
destroyused to also fire every time an already-shown step was shown again, in betweenbefore-showandshow, because the element is recreated on each show. Recreating the element no longer triggersdestroy. See #3443.
You can use the advanceOn option, or the Next button, to advance steps. If you
would like however to have a step advance on a complex user action, you can do
the following:
const myStep = myTour.addStep(options);
yourApp.on('some-event', () => {
if (myStep.isOpen()) {
Shepherd.activeTour.next();
}
});
By default, Shepherd will generate and position an "arrow" element that points
to the target of a step. This is done by setting the arrow option to true on
each ``Step.options` β but you can disable the arrow manually by setting
it to false:
myTour.addStep({
id: 'Step 1',
arrow: false
});
You can also provide an options object, to configure the arrow's padding. The padding is the closest the arrow will get to the edge of the step.
myTour.addStep({
id: 'Step 1',
arrow: { padding: 10 }
});
Furthermore, while Shepherd provides some basic arrow styling, you can style it
as you wish by targeting the .shepherd-arrow element.