Skip to content
Tutorials Center
My learning

Topics

Lesson 38 of 58 ยท JavaScript and Interactivity

Bootstrap JavaScript Plugins

Understand how Bootstrap 5 plugins work: data attributes versus the JavaScript API, getOrCreateInstance, dispose, Popper in the bundle, no jQuery, and module imports.

You have already used Bootstrap's JavaScript without writing any: a button with data-bs-toggle="modal" opens a dialog, a data-bs-dismiss attribute closes it. Behind those attributes sits a set of small plugins, one per interactive component. This lesson explains how they are organized, the two ways to drive them (attributes and code), and the handful of methods every plugin shares.

Understanding this layer matters as soon as content is created dynamically, a component must open after a timer, or you need to react to what a component does. Bootstrap 5 dropped its jQuery dependency, so everything here is plain JavaScript.

The plugins

Each component with behavior is a class on the global bootstrap object when you use the bundle script:

Plugin Used by
bootstrap.Alert dismissible alerts
bootstrap.Button toggle buttons
bootstrap.Carousel carousels
bootstrap.Collapse collapse and accordion
bootstrap.Dropdown dropdown menus
bootstrap.Modal modals
bootstrap.Offcanvas offcanvas panels
bootstrap.Popover and bootstrap.Tooltip popovers and tooltips
bootstrap.ScrollSpy highlighting nav links while scrolling
bootstrap.Tab tabs and pills
bootstrap.Toast toasts

Components such as cards, grids and buttons-as-styling have no JavaScript. Only the interactive ones need a script.

Bundle, Popper and the global

Two files exist on the CDN. bootstrap.bundle.min.js includes Popper, the positioning library used by dropdowns, tooltips and popovers. bootstrap.min.js does not, so you would have to load Popper first yourself. Unless you never use those three components and want to save a few kilobytes, use the bundle, as every lesson here does.

The bundle is a UMD build: it defines a global variable named bootstrap. Load it with a normal <script> tag at the end of the page, before your own script that uses it.

flowchart LR
  A["HTML with<br/>data-bs-* attributes"] --> B["Data API<br/>(listens on document)"]
  C["Your JavaScript"] --> D["JS API<br/>(new bootstrap.X)"]
  B --> P["Plugin class<br/>(Modal, Collapse, ...)"]
  D --> P
  P --> E["Changes classes and ARIA<br/>fires events"]

The data API and the JS API are two doors into the same plugin classes.

Data attributes versus the JavaScript API

The data API is what you have used so far. When the page loads, Bootstrap installs a few click listeners on document. A click on [data-bs-toggle="collapse"] creates (or finds) a Collapse object for the target element and toggles it. You never call new.

The JavaScript API gives the same power from code. You create or fetch a plugin object for an element and call its methods:

JavaScript
const modal = new bootstrap.Modal(document.getElementById('myModal'), {
  backdrop: 'static',
  keyboard: false
});
modal.show();

Options can be written either way. Each option has a data attribute twin: the JS option backdrop is data-bs-backdrop, autoClose is data-bs-auto-close (camelCase becomes kebab-case). When both exist, the object passed in code wins over the attribute, which wins over the plugin default.

Which one should you use? Prefer data attributes for the usual "click a button, something opens" case, because there is no code to maintain. Use the JS API when:

  • an action is not caused by a click on the element itself (a timer, a server response, a keyboard shortcut);
  • the component is opt-in (tooltips, popovers, toasts);
  • you need the return value of a method or want to listen for events.
Opening a collapse from code

The option toggle: false matters for Collapse. Without it, creating the object toggles the panel immediately. The three methods show(), hide() and toggle() are shared by most plugins (Modal, Offcanvas, Collapse, Toast, Tooltip, Popover, Dropdown).

Instances: create, find, reuse, dispose

An instance is the plugin object attached to one element. Bootstrap stores it internally, keyed by element and plugin. Four static methods manage instances:

Method What it does
new bootstrap.Modal(el, options) creates an instance (avoid doing this twice on one element)
bootstrap.Modal.getInstance(el) returns the existing instance, or null if there is none
bootstrap.Modal.getOrCreateInstance(el, options) returns the existing one or creates it
instance.dispose() removes the instance, its stored data and its event listeners

getOrCreateInstance is the one to reach for. If a click handler runs ten times and calls new bootstrap.Modal(el) each time, you create ten objects for the same element, which can lead to duplicated events and confusing state. getOrCreateInstance always gives you the same object. Note that the options only apply when it is created the first time; later calls ignore them.

The element argument can be a DOM element or a CSS selector string such as '#panel'.

The instance lifecycle

After dispose() the HTML element stays on the page, but the plugin no longer controls it. Dispose is useful when you remove a component from the DOM by script or rebuild it with new options, so no listeners are left behind. For plugins that create extra elements (tooltips, popovers), disposing also removes the floating layer.

Methods are asynchronous

When you call modal.hide(), it returns at once, but the modal is still fading out. The visible state changes after the CSS transition. This surprises people who write:

JavaScript
modal.hide();
openAnotherModal(); // runs while the first is still closing

If something must happen after the transition, listen for the event (hidden.bs.modal) instead of assuming. Most plugins also guard against double calls during a transition: a second show() while one is running is ignored.

No jQuery

Bootstrap 4 required jQuery; Bootstrap 5 does not. The plugins are written in plain JavaScript (ES2015 and later), and code that used $('#myModal').modal('show') becomes bootstrap.Modal.getOrCreateInstance('#myModal').show().

For old code, Bootstrap still offers an optional jQuery interface: if jQuery is already loaded on the page when the Bootstrap script runs, the plugins register themselves as jQuery methods. New projects should not rely on it. If you migrate an old site, see the notes in Migrating from Bootstrap 4.

Using modules (build tools)

On the site's live editors you use the CDN bundle. In a project with a bundler (Vite, webpack, esbuild) you install Bootstrap from npm and import only what you need. These snippets are read-only here; they need a build step.

JavaScript
// everything, as a namespace object
import * as bootstrap from 'bootstrap';

// only the plugins you use (smaller output)
import { Modal, Tooltip } from 'bootstrap';

// the bundler needs Popper as a peer dependency:
//   npm install bootstrap @popperjs/core

In module code there is no global bootstrap. Import the class and use it directly: Modal.getOrCreateInstance(el).show(). Popper must be installed because dropdowns, tooltips and popovers use it, even though you do not import it yourself.

Initialize after the page is ready. Scripts placed at the end of <body> run after the markup exists. If your script is in <head>, wait for DOMContentLoaded, or use defer, before searching for elements.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which file contains Popper, the positioning library used by dropdowns, tooltips and popovers?

    The bundle includes Popper. bootstrap.min.js alone expects you to load Popper yourself, and the CSS file contains no JavaScript.
  2. 2. What does bootstrap.Modal.getOrCreateInstance(el) do when a Modal already exists for el?

    It returns the stored instance; it only creates one when none exists. Options passed later are ignored.
  3. 3. Which statement about the Bootstrap 5 plugins is true?

    jQuery was dropped as a requirement in Bootstrap 5. Every plugin can also be used with the JS API.
  4. 4. You call modal.hide() and immediately read whether the modal is hidden. What should you expect?

    Methods start the transition and return. Use the hidden.bs.modal event to know when it is done.
  5. 5. When the same option is set in a data attribute and in the object passed to the constructor, which wins?

    The order is: plugin defaults, then data attributes, then the options object from code.

Summary

  • Every interactive component is a plugin class on the global bootstrap object (or an import in a bundler).
  • The data API (data-bs-*) is the zero-code way; the JS API (new, getOrCreateInstance, show, hide, toggle) is for timers, dynamic content, opt-in components and events.
  • Options can be data attributes or an object; the object wins.
  • getInstance finds, getOrCreateInstance finds or creates, dispose cleans up; avoid repeated new on the same element.
  • Methods start asynchronous transitions; use events to know when they finish.
  • Bootstrap 5 needs no jQuery; module projects import classes and install Popper.

Next lesson: Plugin Events and Programmatic Control.