Bootstrap JavaScript — Programmatic Component Control
In this tutorial, you will learn about Bootstrap JavaScript. We cover key concepts, practical examples, and best practices to help you master this topic.
Bootstrap JavaScript controls interactive components like modals, toasts, carousels, and tooltips with a programmatic API using constructors, methods, events, and data attributes.
What You'll Learn
You will learn how to initialize Bootstrap components with JavaScript, use component methods to control behavior, handle events, and configure options programmatically.
Why It Matters
Programmatic control enables dynamic UI behavior. DodaTech uses Bootstrap's JS API to show modals after API calls, update toasts with live data, and control carousels programmatically.
Real-World Use
Durga Antivirus Pro uses Bootstrap's Modal API to show scan results in a modal after completion, using the show() method and the shown.bs.modal event to lazy-load content.
flowchart LR
A[CSS Variables] --> B[Bootstrap JS]
B --> C[Constructor]
B --> D[Methods]
B --> E[Events]
B --> F[Options]
style B fill:#7952b3,stroke:#563d7c,color:#fff
style C fill:#22c55e,stroke:#16a34a,color:#fff
Accessing Components
<button id="myModalBtn" class="btn btn-primary">Open Modal</button>
<div class="modal fade" id="myModal" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header"><h5 class="modal-title">Programmatic Modal</h5>
<button class="btn-close" data-bs-dismiss="modal"></button></div>
<div class="modal-body">Opened via JavaScript.</div>
</div>
</div>
</div>
<script>
var modalElement = document.getElementById('myModal');
var modal = new bootstrap.Modal(modalElement);
document.getElementById('myModalBtn').addEventListener('click', function () {
modal.show();
});
</script>
Expected output: Clicking the button opens the modal using the JavaScript API instead of data attributes.
Component Methods
// Modal
var modal = new bootstrap.Modal(element, { backdrop: 'static' });
modal.show(); // Open modal
modal.hide(); // Close modal
modal.toggle(); // Toggle visibility
modal.dispose(); // Remove modal instance
// Toast
var toast = new bootstrap.Toast(element, { autohide: false });
toast.show();
toast.hide();
// Carousel
var carousel = new bootstrap.Carousel(element, { interval: 2000 });
carousel.next(); // Next slide
carousel.prev(); // Previous slide
carousel.to(2); // Go to slide index 2
carousel.pause(); // Pause cycling
carousel.cycle(); // Resume cycling
// Tooltip / Popover
var tooltip = new bootstrap.Tooltip(element, { placement: 'right' });
tooltip.show();
tooltip.hide();
tooltip.toggle();
tooltip.dispose();
// Collapse
var collapse = new bootstrap.Collapse(element, { toggle: false });
collapse.show();
collapse.hide();
collapse.toggle();
// Tab
var tab = new bootstrap.Tab(tabElement);
tab.show();
Expected output: Each component can be created, shown, hidden, and disposed of programmatically.
Event Handling
var modal = new bootstrap.Modal(document.getElementById('eventModal'));
var modalEl = document.getElementById('eventModal');
modalEl.addEventListener('show.bs.modal', function () {
console.log('Modal is about to be shown');
});
modalEl.addEventListener('shown.bs.modal', function () {
console.log('Modal is now visible');
});
modalEl.addEventListener('hide.bs.modal', function () {
console.log('Modal is about to be hidden');
});
modalEl.addEventListener('hidden.bs.modal', function () {
console.log('Modal is now hidden');
});
Expected output: Console logs at each stage of the modal lifecycle.
Event Types by Component
| Component | Events |
|---|---|
| Modal | show.bs.modal, shown.bs.modal, hide.bs.modal, hidden.bs.modal |
| Toast | show.bs.toast, shown.bs.toast, hide.bs.toast, hidden.bs.toast |
| Carousel | slide.bs.carousel, slid.bs.carousel |
| Collapse | show.bs.collapse, shown.bs.collapse, hide.bs.collapse, hidden.bs.collapse |
| Tooltip | show.bs.tooltip, shown.bs.tooltip, hide.bs.tooltip, hidden.bs.tooltip |
| Popover | show.bs.popover, shown.bs.popover, hide.bs.popover, hidden.bs.popover |
Configuration Options
// Modal with all options
var modal = new bootstrap.Modal(element, {
backdrop: 'static', // Do not close on backdrop click
keyboard: false, // Do not close on Escape
focus: true // Auto-focus modal
});
// Toast with all options
var toast = new bootstrap.Toast(element, {
animation: true,
autohide: true,
delay: 3000
});
// Carousel with all options
var carousel = new bootstrap.Carousel(element, {
interval: 5000,
pause: 'hover',
wrap: true,
keyboard: true,
touch: true
});
Expected output: Components initialized with custom configuration options.
Dynamic Content Loading
var modal = new bootstrap.Modal(document.getElementById('dynamicModal'));
document.getElementById('loadBtn').addEventListener('click', function () {
var modalBody = document.querySelector('#dynamicModal .modal-body');
modalBody.innerHTML = '<p>Loading...</p>';
modal.show();
// Simulate API call
setTimeout(function () {
modalBody.innerHTML = '<p>Content loaded dynamically after API response.</p>';
}, 1000);
});
Expected output: Clicking the button opens a modal that first shows "Loading..." then replaces the content after a simulated delay.
Common Mistakes
1. Creating Instances Before DOM Ready
If JavaScript runs before the DOM is loaded, element references are null. Wrap code in DOMContentLoaded listener.
2. Not Disposing Instances
Creating multiple instances of the same component without disposing old ones causes memory leaks. Use component.dispose() when removing elements from the DOM.
3. Confusing Constructor and Static Methods
bootstrap.Modal.getInstance(element) returns an existing instance. bootstrap.Modal.getOrCreateInstance(element) creates one if none exists. Use these instead of tracking instances manually.
4. Forgetting to Prevent Default on Events
Some events (like hide.bs.modal) can be cancelled with event.preventDefault() to prevent the action. Not all events support this.
5. Calling Methods Before Initialization
Calling .show() on an uninitialized component throws an error. Always create the instance first or use getOrCreateInstance.
Practice Questions
How do you create a Bootstrap modal instance?
new bootstrap.Modal(element, options)where element is the modal DOM element.What method closes a toast programmatically?
toast.hide()hides a toast instance.How do you listen for a carousel slide change? Add an event listener for
slid.bs.carouselon the carousel element.What is the difference between getInstance and getOrCreateInstance?
getInstancereturns an existing instance or null.getOrCreateInstancecreates one if none exists.How do you prevent a modal from closing? Listen for the
hide.bs.modalevent and callevent.preventDefault().
Challenge
Build a modal that loads external content via fetch when shown. Show a loading spinner initially, then replace with the fetched content. Handle errors by showing an error message in the modal body.
FAQ
Mini Project
Build an admin dashboard that opens a modal to confirm user deletion. When confirmed, show a toast notification with the result. Use Bootstrap's JavaScript API for all interactions without any data attributes.
What's Next
Apply everything you have learned in the Bootstrap Project to build a complete responsive website.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro