Bootstrap JavaScript: Data Attributes, API and Events
The Bootstrap components which need JavaScript (modal, dropdown, collapse, carousel, tabs, tooltip and others) are written in plain JavaScript. Bootstrap 5 does not need jQuery. You can use them in two ways: with data attributes in the HTML, and with the JavaScript API.
1. Data attributes
Most components work with only HTML attributes. Bootstrap reads them, and starts the component when the user clicks.
<button data-bs-toggle="modal" data-bs-target="#myModal">Open</button>
<button data-bs-toggle="collapse" data-bs-target="#info">Toggle</button>
<button data-bs-dismiss="alert">Close</button>
data-bs-togglesays which component to start.data-bs-target(orhref) is the selector of the target element.data-bs-dismisscloses a component.- Options can be given as
data-bs-OPTION, likedata-bs-backdrop="static".
2. The JavaScript API
Every plugin is a class of the global object bootstrap. Create an instance with new, or better, with getOrCreateInstance() which avoids a second instance.
<div class="alert alert-success" id="a1" role="alert">An alert that we will control with code.</div>
console.log('Bootstrap version: ' + bootstrap.Modal.VERSION);
console.log('available plugins: ' + ['Alert','Button','Carousel','Collapse','Dropdown','Modal','Offcanvas','Popover','ScrollSpy','Tab','Toast','Tooltip'].filter(n => typeof bootstrap[n] === 'function').join(', '));
const el = document.getElementById('a1');
const inst = bootstrap.Alert.getOrCreateInstance(el);
console.log('same instance again: ' + (bootstrap.Alert.getOrCreateInstance(el) === inst));
console.log('getInstance returns it: ' + (bootstrap.Alert.getInstance(el) === inst));
inst.close();
await new Promise(r => setTimeout(r, 600));
console.log('alert in the page after close(): ' + document.querySelectorAll('#a1').length);
Bootstrap version: 5.3.8
available plugins: Alert, Button, Carousel, Collapse, Dropdown, Modal, Offcanvas, Popover, ScrollSpy, Tab, Toast, Tooltip
same instance again: true
getInstance returns it: true
alert in the page after close(): 0
| Method | Meaning |
|---|---|
new bootstrap.Modal(el, options) | Make a new instance |
bootstrap.Modal.getInstance(el) | Get the existing instance (or null) |
bootstrap.Modal.getOrCreateInstance(el) | Get it, or make it if it does not exist |
instance.dispose() | Remove the instance and its data |
Plugin.VERSION | The Bootstrap version |
3. Events
Each plugin sends events. They have the name of the action and the plugin, like show.bs.modal. The event “show” runs before it starts, and “shown” after the animation. You can stop a “show” or “hide” event with event.preventDefault().
<div class="collapse" id="ev1"><div class="card card-body">Collapse content</div></div>
const el = document.getElementById('ev1');
const log = [];
['show', 'shown', 'hide', 'hidden'].forEach(name => {
el.addEventListener(name + '.bs.collapse', () => log.push(name));
});
const c = bootstrap.Collapse.getOrCreateInstance(el, { toggle: false });
c.show();
await new Promise(r => setTimeout(r, 700));
c.hide();
await new Promise(r => setTimeout(r, 700));
console.log('events in order: ' + log.join(' -> '));
events in order: show -> shown -> hide -> hidden
Options
You can give options in the second argument of the constructor, or as data attributes. If you use both, the JavaScript options win over the data attributes.
new bootstrap.Modal('#myModal', { backdrop: 'static', keyboard: false });
new bootstrap.Tooltip('#myTip', { placement: 'right', trigger: 'focus' });
Good habits
- Load the JavaScript after the HTML, at the end of the body, and after the Bootstrap file.
- Start the opt-in plugins (tooltip, popover) with a small script.
- Use
getOrCreateInstance(), and do not create the same plugin twice on one element. - Use
dispose()when you remove an element from the page, if you use a single page application. - If you use a framework like React or Vue, use a wrapper library or the API carefully, because both want to control the DOM.
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |