BootstrapBundle.js
Big things in big packages
Bootstrap 5 includes a powerful collection of JavaScript plugins that extend the functionality of its components. These plugins provide interactive features like dropdowns, modals, tooltips, and more without requiring you to write complex JavaScript code.
Installation
Include Bootstrap's JavaScript bundle after the CSS:
<!-- Bootstrap CSS -->
<link href="path/to/bootstrap.min.css" rel="stylesheet">
<!-- Bootstrap Bundle JS (includes Popper) -->
<script src="path/to/bootstrap.bundle.min.js"></script>
Or include individual plugins as needed:
<!-- Just Popper.js and specific plugins -->
<script src="path/to/popper.min.js"></script>
<script src="path/to/bootstrap/js/dist/modal.js"></script>
<script src="path/to/bootstrap/js/dist/tooltip.js"></script>
Initialization
Bootstrap components can be initialized in two ways:
Via Data Attributes
<!-- Initialize a modal via data attributes -->
<button type="button" data-bs-toggle="modal" data-bs-target="#exampleModal">
Launch modal
</button>
Via JavaScript
// Initialize a modal via JavaScript
var myModal = new bootstrap.Modal(document.getElementById('exampleModal'), {
backdrop: 'static',
keyboard: false
});
Core JavaScript Components
Alerts
// Dismiss an alert via JavaScript
var alertNode = document.querySelector('.alert')
var alert = bootstrap.Alert.getInstance(alertNode)
alert.close()
// Via data attributes
<div class="alert alert-warning alert-dismissible fade show" role="alert">
<strong>Holy guacamole!</strong> You should check in on some of those fields below.
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
Modals
// Create a modal instance
var myModal = new bootstrap.Modal(document.getElementById('myModal'), {
backdrop: true,
focus: true,
keyboard: true
})
// Show and hide methods
myModal.show()
myModal.hide()
myModal.toggle()
myModal.handleUpdate() // Readjust modal position in case of height changes
// Events
myModal.addEventListener('show.bs.modal', function () {
// do something when modal is about to be shown
})
myModal.addEventListener('shown.bs.modal', function () {
// do something when modal is shown
})
Tooltips
// Initialize all tooltips on a page
var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'))
var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
return new bootstrap.Tooltip(tooltipTriggerEl)
})
// Options
var tooltip = new bootstrap.Tooltip(element, {
boundary: 'clippingParents',
customClass: 'custom-tooltip',
delay: { show: 500, hide: 100 },
html: true,
placement: 'auto',
template: '<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>',
trigger: 'hover focus'
})
Official Tooltip Documentation
Popovers
// Initialize all popovers
var popoverTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="popover"]'))
var popoverList = popoverTriggerList.map(function (popoverTriggerEl) {
return new bootstrap.Popover(popoverTriggerEl)
})
// With options
var popover = new bootstrap.Popover(document.querySelector('.example-popover'), {
container: 'body',
content: 'This is popover content',
html: true,
placement: 'right',
sanitize: true,
trigger: 'focus'
})
Carousel
The carousel is a slideshow component for cycling through elements:
// Initialize a carousel
var myCarousel = document.querySelector('#myCarousel')
var carousel = new bootstrap.Carousel(myCarousel, {
interval: 2000, // Time between slide transitions (ms)
keyboard: true, // React to keyboard events
pause: 'hover', // Pause on mouse enter
ride: false, // Autoplays on page load
wrap: true, // Cycles continuously
touch: true // Supports swipe gestures
})
// Methods
carousel.cycle() // Start cycling through items
carousel.pause() // Pause the carousel
carousel.prev() // Cycle to previous item
carousel.next() // Cycle to next item
carousel.to(2) // Cycle to a particular item (0-based)
carousel.dispose() // Destroys the carousel
// Events
myCarousel.addEventListener('slide.bs.carousel', function () {
// Fires immediately when the slide transition is invoked
})
myCarousel.addEventListener('slid.bs.carousel', function () {
// Fires when the carousel has completed its slide transition
})
Utility Components
Toasts
// Initialize a toast
var toastElList = [].slice.call(document.querySelectorAll('.toast'))
var toastList = toastElList.map(function (toastEl) {
return new bootstrap.Toast(toastEl, {
autohide: true,
delay: 5000
})
})
// Show a toast
toastList.forEach(toast => toast.show())
// Methods
var myToast = bootstrap.Toast.getInstance(document.getElementById('myToast'))
myToast.show()
myToast.hide()
// Via data attributes
<div class="toast" role="alert" aria-live="assertive" aria-atomic="true" data-bs-autohide="true" data-bs-delay="5000">
<div class="toast-header">
<strong class="me-auto">Bootstrap</strong>
<small>11 mins ago</small>
<button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
</div>
<div class="toast-body">
Hello, world! This is a toast message.
</div>
</div>
Scrollspy
// Initialize scrollspy via JavaScript
var scrollSpy = new bootstrap.ScrollSpy(document.body, {
target: '#navbar-example'
})
// Get the current ScrollSpy instance
var dataSpyList = [].slice.call(document.querySelectorAll('[data-bs-spy="scroll"]'))
dataSpyList.forEach(function (dataSpyEl) {
bootstrap.ScrollSpy.getInstance(dataSpyEl)
.refresh() // Recalculate element positions and offsets
})
// Via data attributes
<body data-bs-spy="scroll" data-bs-target="#navbar-example" data-bs-offset="0" tabindex="0">
<nav id="navbar-example">
<ul class="nav nav-tabs">
<li class="nav-item"><a class="nav-link" href="#fat">@fat</a></li>
<li class="nav-item"><a class="nav-link" href="#mdo">@mdo</a></li>
</ul>
</nav>
<div data-bs-spy="scroll" data-bs-target="#navbar-example" data-bs-offset="0" class="scrollspy-example">
<h4 id="fat">@fat</h4>
<p>...</p>
<h4 id="mdo">@mdo</h4>
<p>...</p>
</div>
</body>
Form Components
Form Validation
// Example starter JavaScript for disabling form submissions if there are invalid fields
(function () {
'use strict'
// Fetch all the forms we want to apply custom Bootstrap validation styles to
var forms = document.querySelectorAll('.needs-validation')
// Loop over them and prevent submission
Array.prototype.slice.call(forms)
.forEach(function (form) {
form.addEventListener('submit', function (event) {
if (!form.checkValidity()) {
event.preventDefault()
event.stopPropagation()
}
form.classList.add('was-validated')
}, false)
})
})()
// HTML structure
<form class="needs-validation" novalidate>
<div class="mb-3">
<label for="validationCustom01" class="form-label">First name</label>
<input type="text" class="form-control" id="validationCustom01" value="Mark" required>
<div class="valid-feedback">
Looks good!
</div>
</div>
<div class="mb-3">
<label for="validationCustom02" class="form-label">Last name</label>
<input type="text" class="form-control" id="validationCustom02" value="Otto" required>
<div class="invalid-feedback">
Please provide a last name.
</div>
</div>
<button class="btn btn-primary" type="submit">Submit form</button>
</form>
Best Practices
- Use data attributes for simple implementations and JavaScript for more complex scenarios
- Initialize components that aren't automatically activated (like tooltips and popovers)
- Use event listeners to respond to component state changes
- Ensure Popper.js is included when using tooltips, popovers, or dropdowns
- Use the dispose method to clean up components when they're no longer needed
data-bs-toggle="tooltip"
on a parent element and initialize once, rather than initializing each tooltip individually.
Troubleshooting
- Components not working? Make sure you've included bootstrap.bundle.min.js which contains Popper.js.
- Tooltips or popovers not showing? Remember they must be initialized manually with JavaScript.
- Modal backdrop issues? Check for proper z-index values and ensure you're not nesting modals incorrectly.
- Scrollspy not highlighting correctly? Verify your target elements have the correct IDs and enough content to scroll.
- Form validation not working? Ensure you've added the 'needs-validation' class and 'novalidate' attribute to your form.