Bootstrap 5 Tutorial
v5.3.0Bootstrap 5 Tutorial
JavaScript Integration in Bootstrap 5
Bootstrap's JavaScript Architecture
Bootstrap 5 includes interactive components that require JavaScript. Unlike Bootstrap 4, version 5 is vanilla JavaScript (no jQuery dependency), making it lighter and more modern.
Bootstrap 4 (with jQuery)
<!-- Bootstrap 4 dependencies -->
<script src="jquery.min.js"></script>
<script src="popper.js"></script>
<script src="bootstrap.min.js"></script>
// jQuery required
$('#myModal').modal('show');Heavier (requires jQuery)
Bootstrap 5 (Vanilla JS)
<!-- Bootstrap 5 dependencies -->
<script src="bootstrap.bundle.min.js"></script>
// Pure JavaScript
var myModal = new bootstrap.Modal(
document.getElementById('myModal')
);
myModal.show();Lighter (no jQuery)
Including Bootstrap JavaScript
Installation Methods
CDN (Recommended)
<!-- Bundle (includes Popper) -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<!-- Separate files -->
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.8/dist/umd/popper.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.min.js"></script>npm Package
# Install via npm
npm install bootstrap @popperjs/core
// Import in your JavaScript
import 'bootstrap/dist/css/bootstrap.min.css';
import 'bootstrap';Download Manually
<!-- Download from getbootstrap.com -->
<script src="/path/to/bootstrap.bundle.min.js"></script>
<!-- Or separate -->
<script src="/path/to/popper.min.js"></script>
<script src="/path/to/bootstrap.min.js"></script>Recommendation:
Use the bundled version (bootstrap.bundle.min.js) which includes Popper.js. This is the simplest approach for most projects.
JavaScript Components
Available Components
Modal
Dialog boxes/popups
Dropdown
Toggleable menus
Tooltip
Small popup hints
Popover
Popup with content
Collapse
Show/hide content
Carousel
Slideshow component
| Component | Data Attribute | JavaScript Class | Description |
|---|---|---|---|
| Modal | data-bs-toggle="modal" | bootstrap.Modal | Dialog boxes/popups |
| Dropdown | data-bs-toggle="dropdown" | bootstrap.Dropdown | Toggleable context menus |
| Tooltip | data-bs-toggle="tooltip" | bootstrap.Tooltip | Small hover popups |
| Popover | data-bs-toggle="popover" | bootstrap.Popover | Popup with title & content |
| Collapse | data-bs-toggle="collapse" | bootstrap.Collapse | Show/hide content |
| Carousel | data-bs-slide | bootstrap.Carousel | Slideshow component |
| Toast | data-bs-toggle="toast" | bootstrap.Toast | Push notifications |
| Alert | data-bs-dismiss="alert" | bootstrap.Alert | Dismissible alerts |
Initializing Components
Component Initialization Methods
Method 1: Data Attributes (Recommended)
Initialize components automatically using HTML data attributes.
<!-- Modal with data attributes -->
<button type="button"
class="btn btn-primary"
data-bs-toggle="modal"
data-bs-target="#exampleModal">
Launch modal
</button>
<!-- Modal structure -->
<div class="modal fade" id="exampleModal">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal content -->
</div>
</div>
</div>
<!-- No JavaScript required! -->Method 2: JavaScript API
Initialize components programmatically using JavaScript.
// Get modal element
var myModalEl = document.getElementById('myModal');
// Create modal instance
var myModal = new bootstrap.Modal(myModalEl, {
backdrop: 'static', // Modal doesn't close on click
keyboard: false // Modal doesn't close on ESC
});
// Show modal
myModal.show();
// Hide modal
myModal.hide();
// Toggle modal
myModal.toggle();When to Use Each Method:
- Data Attributes: Simple use cases, static content
- JavaScript API: Dynamic content, complex interactions, programmatic control
- Mixed Approach: Use data attributes for basic setup, enhance with JavaScript
Event Handling
Bootstrap JavaScript Events
Bootstrap components emit events that you can listen to for custom functionality.
Modal Events Example
// Get modal element
var myModal = document.getElementById('myModal');
// Listen for modal events
myModal.addEventListener('show.bs.modal', function (event) {
// Fires when modal is about to show
console.log('Modal is about to show');
// Access related target (button that triggered)
var button = event.relatedTarget;
console.log('Triggered by:', button);
});
myModal.addEventListener('shown.bs.modal', function () {
// Fires when modal is fully shown
console.log('Modal is now visible');
});
myModal.addEventListener('hide.bs.modal', function () {
// Fires when modal is about to hide
console.log('Modal is about to hide');
});
myModal.addEventListener('hidden.bs.modal', function () {
// Fires when modal is fully hidden
console.log('Modal is now hidden');
});Common Events by Component
| Component | Events |
|---|---|
| Modal | show.bs.modalshown.bs.modalhide.bs.modalhidden.bs.modal |
| Dropdown | show.bs.dropdownshown.bs.dropdownhide.bs.dropdownhidden.bs.dropdown |
| Carousel | slide.bs.carouselslid.bs.carousel |
| Collapse | show.bs.collapseshown.bs.collapsehide.bs.collapsehidden.bs.collapse |
| Toast | show.bs.toastshown.bs.toasthide.bs.toasthidden.bs.toast |
Event Naming Pattern:
{action}.bs.{component}
Example: show.bs.modal (fires before modal shows)shown.bs.modal (fires after modal is shown)
Methods & Options
JavaScript API Methods
Modal Methods
// Get modal instance
var myModal = new bootstrap.Modal(
document.getElementById('myModal')
);
// Available methods
myModal.show(); // Shows modal
myModal.hide(); // Hides modal
myModal.toggle(); // Toggles modal
myModal.handleUpdate(); // Updates modal position
myModal.dispose(); // Destroys modal instance
// Modal options
var modal = new bootstrap.Modal(el, {
backdrop: true, // Show backdrop
keyboard: true, // Close on ESC
focus: true // Focus on modal when shown
});Tooltip Methods
// Initialize tooltip
var tooltip = new bootstrap.Tooltip(
document.querySelector('[data-bs-toggle="tooltip"]')
);
// Available methods
tooltip.show(); // Shows tooltip
tooltip.hide(); // Hides tooltip
tooltip.toggle(); // Toggles tooltip
tooltip.enable(); // Enables tooltip
tooltip.disable(); // Disables tooltip
tooltip.toggleEnabled(); // Toggles enabled state
tooltip.dispose(); // Destroys tooltip instance
// Tooltip options
var tooltip = new bootstrap.Tooltip(el, {
animation: true, // Fade animation
delay: {show: 100, hide: 100}, // Delay in ms
placement: 'top', // Position
title: 'Tooltip text' // Content
});Common Component Options:
| Option | Type | Default | Description |
|---|---|---|---|
backdrop | boolean/string | true | Includes a backdrop element. Use 'static' for non-dismissible backdrop. |
keyboard | boolean | true | Closes the component when ESC key is pressed |
focus | boolean | true | Puts focus on the component when initialized |
animation | boolean | true | Apply a CSS fade transition to the component |
delay | number/object | 0 | Delay showing and hiding (ms) |
placement | string | 'top' | Position of tooltip/popover |
Integration with Frameworks
Framework-Specific Integration
React Integration
Use React Bootstrap or Bootstrap components with React lifecycle methods.
// Using react-bootstrap
import { Modal, Button } from 'react-bootstrap';
function MyModal() {
const [show, setShow] = useState(false);
return (
<>
<Button onClick={() => setShow(true)}>
Show Modal
</Button>
<Modal show={show} onHide={() => setShow(false)}>
<Modal.Header closeButton>
<Modal.Title>Modal Title</Modal.Title>
</Modal.Header>
<Modal.Body>Modal content</Modal.Body>
</Modal>
</>
);
}
// Manual integration
useEffect(() => {
// Initialize Bootstrap components
var tooltips = document.querySelectorAll('[data-bs-toggle="tooltip"]');
tooltips.forEach(tooltip => {
new bootstrap.Tooltip(tooltip);
});
// Cleanup on unmount
return () => {
tooltips.forEach(tooltip => {
var instance = bootstrap.Tooltip.getInstance(tooltip);
if (instance) instance.dispose();
});
};
}, []);Vue.js Integration
Use BootstrapVue or direct integration with Vue lifecycle hooks.
// Using BootstrapVue
<template>
<b-button v-b-modal.my-modal>Show Modal</b-button>
<b-modal id="my-modal" title="Modal Title">
<p>Modal content</p>
</b-modal>
</template>
<script>
import { BootstrapVue, BModal, BButton } from 'bootstrap-vue';
Vue.use(BootstrapVue);
export default {
components: {
BModal,
BButton
}
}
</script>
// Manual integration
export default {
mounted() {
// Initialize Bootstrap components
this.initializeBootstrap();
},
methods: {
initializeBootstrap() {
// Initialize tooltips
var tooltips = this.$el.querySelectorAll('[data-bs-toggle="tooltip"]');
tooltips.forEach(el => {
new bootstrap.Tooltip(el);
});
}
},
beforeUnmount() {
// Cleanup Bootstrap instances
var tooltips = this.$el.querySelectorAll('[data-bs-toggle="tooltip"]');
tooltips.forEach(el => {
var instance = bootstrap.Tooltip.getInstance(el);
if (instance) instance.dispose();
});
}
}Framework Integration Tips:
- Use official wrapper libraries: React Bootstrap, BootstrapVue, ng-bootstrap
- Initialize in lifecycle hooks:
componentDidMount,mounted,ngOnInit - Clean up on unmount: Dispose Bootstrap instances to prevent memory leaks
- Consider virtual DOM: Direct DOM manipulation may conflict with framework updates
- Use refs/references: Access DOM elements through framework references, not direct selectors
Common Issues & Solutions
Troubleshooting JavaScript Issues
| Issue | Cause | Solution |
|---|---|---|
| Components not working | JavaScript not loaded or loaded too early | Load Bootstrap JS before closing </body> tag |
| Tooltips/popovers not showing | Not initialized or missing Popper.js | Initialize manually or use bundle version |
| Modal backdrop issues | Multiple modals or z-index conflicts | Ensure proper modal nesting and z-index |
| Dropdown not closing | Event propagation issues | Check for JavaScript errors or event handlers |
| Carousel not sliding | Missing slide items or incorrect structure | Verify carousel HTML structure |
| Memory leaks | Not disposing instances | Call dispose() when removing elements |
| Console errors | Conflicting jQuery or other libraries | Check console for specific errors |
Debugging Tips:
Check Component Initialization:
// Check if component is initialized
var modal = bootstrap.Modal.getInstance(
document.getElementById('myModal')
);
console.log(modal); // Should return instance or nullVerify Event Listeners:
// Check event listeners
var el = document.getElementById('myButton');
console.log(el); // Inspect in browser console
// Check Event Listeners tab in DevToolsBest Practices
JavaScript Integration Best Practices
- Use the bundled version:
bootstrap.bundle.min.jsincludes Popper.js - Load scripts at the bottom: Place before closing
</body>tag for performance - Initialize dynamically created components: Call constructor for elements added after page load
- Dispose instances properly: Call
dispose()when removing elements to prevent memory leaks - Use event delegation: Attach event listeners to parent elements for dynamic content
- Check for existing instances: Use
getInstance()before creating new instances - Follow accessibility guidelines: Ensure keyboard navigation and screen reader support
- Test across browsers: Verify functionality in all target browsers
- Keep it simple: Use data attributes when possible, enhance with JavaScript when needed
- Document custom implementations: Comment complex JavaScript interactions
Performance Optimization
Lazy Initialization
Initialize components only when needed, not all at page load.
// Lazy initialize tooltips
function initializeTooltips() {
// Only initialize visible tooltips
var visibleTooltips = Array.from(
document.querySelectorAll('[data-bs-toggle="tooltip"]')
).filter(el => el.offsetParent !== null); // Check if visible
visibleTooltips.forEach(el => {
if (!bootstrap.Tooltip.getInstance(el)) {
new bootstrap.Tooltip(el);
}
});
}
// Initialize on demand
document.getElementById('showTips').addEventListener('click', function() {
initializeTooltips();
});
// Or initialize when element comes into view
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
var el = entry.target;
if (el.hasAttribute('data-bs-toggle')) {
// Initialize component
}
}
});
});Selective Loading
Load only the Bootstrap components you need.
// Import individual components
import Alert from 'bootstrap/js/dist/alert';
import Button from 'bootstrap/js/dist/button';
import Modal from 'bootstrap/js/dist/modal';
import Tooltip from 'bootstrap/js/dist/tooltip';
// Or use tree-shaking with bundlers
// Webpack, Rollup, Parcel will remove unused code
// Manual selective loading (CDN alternative)
// Load only modal and tooltip componentsBundle Size Comparison:
- Full bundle: ~60KB (gzipped)
- Modal only: ~10KB (gzipped)
- Tooltip only: ~15KB (gzipped)
- Dropdown only: ~12KB (gzipped)
Quick Reference
data-bs-toggle="modal"- Modal triggernew bootstrap.Modal(el)- JS initializationshow.bs.modal- Modal show eventmyModal.dispose()- Clean up instancebootstrap.Modal.getInstance(el)- Get existing instancebootstrap.bundle.min.js- Recommended bundle