Skip to content
Tutorials Center
My learning

Topics

Lesson 39 of 58 ยท JavaScript and Interactivity

Plugin Events and Programmatic Control

Listen to Bootstrap 5 plugin events such as show.bs.modal and hidden.bs.collapse, cancel actions with preventDefault, control components from code, and use ScrollSpy.

Bootstrap components do not only react to clicks; they also announce what they are doing. When a modal starts to open, finishes opening, starts to close or finishes closing, it fires a DOM event on its element. Your code can listen for these events to load data, move focus, reset a form, block a close, or keep other parts of the page in step.

This lesson builds on Bootstrap JavaScript Plugins. You will learn the event naming scheme, how to cancel an action with preventDefault(), how to open and close components from code, and how the ScrollSpy plugin highlights a navigation link while the page scrolls. The examples print what happens on the page itself, so you can watch the order of events.

Event names

Bootstrap events follow one pattern: <verb>.bs.<plugin>. The suffix .bs.<plugin> is a namespace; it is simply part of the event's name, so you pass the whole string to addEventListener.

For most plugins, the verbs come in pairs:

Verb Fires Cancelable
show when show() is called (the "about to" event) yes
shown when the transition has finished and the component is visible no
hide when hide() is called yes
hidden when the component is completely hidden no

The same four exist for modal, offcanvas, collapse, dropdown, tab, toast, tooltip and popover (inserted.bs.tooltip is a bonus event). Other plugins have their own:

Event Plugin Detail
slide.bs.carousel, slid.bs.carousel Carousel event.direction, event.from, event.to
close.bs.alert, closed.bs.alert Alert close is cancelable
hidePrevented.bs.modal Modal a close attempt was blocked
activate.bs.scrollspy ScrollSpy event.relatedTarget is the link that became active

The event is dispatched on the component's element and it bubbles. So you can listen on the element itself, or on document and filter with event.target. Because events bubble, a listener on document hears every component on the page, and nested components (a dropdown inside a collapse, for example) can fire events of the same kind that reach an outer listener. Check event.target when that matters.

sequenceDiagram
  participant Code as Your code
  participant P as Plugin
  participant E as Element
  Code->>P: show()
  P->>E: fires show.bs.modal
  Note over E: listeners may call preventDefault()
  P->>E: transition runs (CSS)
  P->>E: fires shown.bs.modal

Opening a component: the cancelable "show" event comes first, the "shown" event comes after the transition.

Watch the event order

Press the button twice and you will see all four names in order. Notice that show and shown arrive at slightly different times: show is immediate, shown waits for the CSS transition.

Cancelling with preventDefault()

The "about to" events (show, hide, slide, close) are cancelable. Call event.preventDefault() in the listener and the action does not happen. Use this to protect unsaved work, to wait for a condition, or to forbid a tab switch.

Be careful with the other half: the "-ed" events (shown, hidden, closed) report something that has already happened, so cancelling them does nothing.

A common pattern is a modal with a form: if the user typed something, the modal should not close accidentally. The listener below checks the text area on hide.bs.modal. If there is unsaved text it cancels the close and asks first; a "Discard" button clears the text and closes for real.

Block closing with unsaved text

Try it: type a few words and press the X. The modal stays open and the red warning appears. Press "Discard and close" or "Save" and it closes. The flag allowClose tells the hide listener that this particular close is intended. Without such a flag, modal.hide() in the buttons would be cancelled by the same listener.

Also note shown.bs.modal is used to focus the text area, and hidden.bs.modal resets the form. A good rule: prepare in show, act in shown, clean up in hidden.

Controlling components from code

The methods you met before are the other half of the toolbox:

  • show(), hide() and toggle() exist on Modal, Offcanvas, Collapse, Toast, Dropdown, Tooltip and Popover.
  • Tab has show() to activate a tab; Carousel has next(), prev(), to(index), pause(), cycle().
  • Tooltip and Popover have enable(), disable() and update() (reposition), and setContent() to change text on the fly.
  • Modal.handleUpdate() adjusts the modal after the content height changes.

Because events fire in response to these calls as well as to clicks, a single listener covers every way a component can open. That is one strong reason to write behavior in an event listener instead of in the code that triggers the action.

JavaScript
// Switch to the "Billing" tab from code and react to the change
const trigger = document.querySelector('#billing-tab');
trigger.addEventListener('shown.bs.tab', (event) => {
  console.log('Now showing', event.target.id);
  console.log('Previously', event.relatedTarget?.id);
});
bootstrap.Tab.getOrCreateInstance(trigger).show();

For tabs, event.target is the newly active tab button and event.relatedTarget is the previous one.

ScrollSpy

ScrollSpy updates a navigation list as the visitor scrolls: the link of the section on screen becomes active. It is the table-of-contents highlight you see on long documentation pages.

It needs three things:

  1. A scrollable container (or the body) with data-bs-spy="scroll" and data-bs-target="#nav", pointing at the navigation element. If the container is a box rather than the page, give it position: relative, a fixed height and overflow-y: auto, and tabindex="0" so keyboard users can scroll it.
  2. A navigation (.nav, .list-group) whose links have href="#section-id".
  3. Sections with matching id attributes inside the container.

Bootstrap 5.3 detects the current section with an IntersectionObserver. The option data-bs-root-margin (default 0px 0px -25%) shrinks the observed area so a section becomes active a little before it reaches the middle of the view, and data-bs-smooth-scroll="true" animates clicks on the links.

ScrollSpy in a scrollable box

The activate.bs.scrollspy event fires on the navigation element with the newly active link in event.relatedTarget. If you add or remove sections dynamically, call bootstrap.ScrollSpy.getInstance(box).refresh() so the plugin re-reads the page.

Common ScrollSpy problems. The target links must be real in-page anchors (href="#id") and each id must exist; a link without a matching section is ignored. A container that does not scroll, or sections that are too short to ever occupy the observed area, make the last link impossible to activate.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which event fires after a modal has finished its closing transition?

    hide fires when closing starts, hidden when it is complete. hidePrevented is for blocked close attempts.
  2. 2. How do you stop a modal from closing from inside a listener?

    Only the cancelable 'about to' events can be stopped, and the way to do it is preventDefault(). Events ending in -ed have already happened.
  3. 3. Where is the best place to focus a form field inside a modal?

    The field cannot take focus until the modal is visible, which is after the transition, at shown.bs.modal.
  4. 4. What does ScrollSpy put on the link of the section currently in view?

    ScrollSpy toggles active on the matching navigation link and fires activate.bs.scrollspy.
  5. 5. Why is it usually better to put behavior in an event listener than in the code that opens the component?

    Events fire for every route that opens or closes the component, so one listener covers them all.

Summary

  • Plugin events are named verb.bs.plugin and fire on the component's element; they bubble.
  • show, hide, slide and close are cancelable with event.preventDefault(); the -ed events (shown, hidden) are notifications only.
  • Use show to prepare, shown to focus or measure, and hidden to reset.
  • Components can be controlled with show, hide, toggle, and plugin-specific methods such as Carousel.to().
  • ScrollSpy marks the nav link of the visible section active, needs matching ids and a scrolling container, and fires activate.bs.scrollspy.

Next lesson: Customizing with CSS Variables.