navigations

Tailwind CSS Scrollspy

Automatically adjust navigation or list group components based on scroll position to highlight the link that is currently active in the viewport.

Class Name
Type
Description
scrollspy-active:{tw-utility-class}ModifierAdds tailwindCSS classes when navigation link is active.

Set the values for the attributes data-scrollspy and data-scrollspy-scrollable-parent to designate the scrollspy component and its corresponding parent container, targeting their respective Id’s.

Include the attribute data-scrollspy-group for nested anchors to ensure that the parent link remains active when the child link is active.

The following example illustrates a fundamental scrollspy component.

Below given example demonstrates scrollspy component with navbar.

Below given example demonstrates scrollspy component with list group.

Utilize the option [--scrollspy-offset:number] to adjust the scroll offset from the top for the scrollspy component. By default, its value is set to 0.

Below given example illustrates usage of scrollspy-offset option.

PARAMETERS
DESCRIPTION
OPTIONS
DEFAULT VALUE
data-scrollspyA container containing sections. This must be a valid selector.string-
data-scrollspy-scrollable-parentSpecifies the element to be scrolled. This must be a valid selector.stringwindow
--scrollspy-offset:*Adds offset when scrolling to the section and to determine if the section is active.number0

The HSScrollspy object is contained within the global window object.

METHOD
DESCRIPTION
HSScrollspy.getInstance(target, isInstance)
Returns the element associated to the target.
  • target should be a Node or string (valid selector).
  • isInstance boolean. Returns the instance instead of Node if true.
METHOD
DESCRIPTION
RETURNING VALUE
on:beforeScrollCalled before scrolling begins. Could be Promise.Instance

Assign an ID to the button containing the data-scrollspy attribute, and then use that ID to attach an event.

The following example illustrates how events are utilized in smaller screens. In this scenario, the collapse component is triggered by clicking on the (hamburger) menu. When links within the collapse content are clicked, the on:beforeScroll event is triggered to close it before scrolling.

Call any function on `beforeScroll` example.

// This method/event is used in above example.
const el = HSScrollspy.getInstance('[data-scrollspy="#scrollspy"]', true);
const collapse = HSCollapse.getInstance('[data-collapse="#navbar-collapse-basic"]', true);

el.element.on('beforeScroll', (instance) => {
return new Promise((res) => {
if (collapse.element.el.classList.contains('open')) {
collapse.element.hide();
StaticMethods.afterTransition(collapse.element.content, () => res(true));
} else {
res(true);
}
});
});