Bootstrap JavaScript: Data Attributes & API

Bootstrap Framework 10 min min read Updated: Nov 16, 2026 Advanced
Bootstrap JavaScript: Data Attributes & API
Advanced Topic 4 of 10

Two Ways to Use Bootstrap JavaScript

WayHowBest For
Data attributesWrite data-bs-* in HTML onlySimple pages
JavaScript APICreate and control components in codeDynamic apps

Data Attributes

Most of the time you do not write any JavaScript. Bootstrap watches the page for data attributes and does the work.

html <button data-bs-toggle="modal" data-bs-target="#myModal">Open</button> <button data-bs-dismiss="modal">Close</button> <button data-bs-toggle="collapse" data-bs-target="#info">Toggle</button>

Options can also be set as data attributes by adding the option name: data-bs-backdrop="static".

Creating Components with JavaScript

javascript const el = document.getElementById('myModal'); // Create a new instance const modal = new bootstrap.Modal(el, { backdrop: 'static', keyboard: false }); modal.show(); modal.hide(); modal.toggle();

getOrCreateInstance

Creating the same component twice can cause bugs. Use getOrCreateInstance to reuse an existing one:

javascript const modal = bootstrap.Modal.getOrCreateInstance(document.getElementById('myModal')); modal.show();

Common Methods

ComponentMethods
Modal, Offcanvasshow(), hide(), toggle(), dispose()
Collapseshow(), hide(), toggle()
Carouselnext(), prev(), pause(), cycle(), to(index)
Tabshow()
Toastshow(), hide()
Tooltip, Popovershow(), hide(), enable(), disable()

Events

Components fire events when they open or close. Event names look like show.bs.modal, shown.bs.modal, hide.bs.modal and hidden.bs.modal.

javascript const el = document.getElementById('myModal'); el.addEventListener('shown.bs.modal', () => { document.getElementById('nameInput').focus(); }); el.addEventListener('hidden.bs.modal', () => { document.getElementById('myForm').reset(); });
show vs shown: show fires at the start, right when the open command is called. shown fires after the animation has finished. The same applies to hide and hidden.

Example: Open a Modal After 3 Seconds

javascript setTimeout(() => { bootstrap.Modal.getOrCreateInstance('#promoModal').show(); }, 3000);

Conclusion

You can build many things using only data attributes. When you need more control, the JavaScript API lets you open, close and react to every component.

Quick Summary: Use data-bs-* for simple work, new bootstrap.Component() or getOrCreateInstance for control, and listen to events like shown.bs.modal.

Get Newsletter

Subscibe to our newsletter and we will notify you about the newest updates on Edugators