Bootstrap 5 Tutorial

v5.3.0

Bootstrap 5 Tutorial

JavaScript Integration in Bootstrap 5

JavaScript Integration: Learn how Bootstrap's JavaScript components work and how to integrate them with your own JavaScript code.

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

ComponentData AttributeJavaScript ClassDescription
Modaldata-bs-toggle="modal"bootstrap.ModalDialog boxes/popups
Dropdowndata-bs-toggle="dropdown"bootstrap.DropdownToggleable context menus
Tooltipdata-bs-toggle="tooltip"bootstrap.TooltipSmall hover popups
Popoverdata-bs-toggle="popover"bootstrap.PopoverPopup with title & content
Collapsedata-bs-toggle="collapse"bootstrap.CollapseShow/hide content
Carouseldata-bs-slidebootstrap.CarouselSlideshow component
Toastdata-bs-toggle="toast"bootstrap.ToastPush notifications
Alertdata-bs-dismiss="alert"bootstrap.AlertDismissible 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
ComponentEvents
Modalshow.bs.modal
shown.bs.modal
hide.bs.modal
hidden.bs.modal
Dropdownshow.bs.dropdown
shown.bs.dropdown
hide.bs.dropdown
hidden.bs.dropdown
Carouselslide.bs.carousel
slid.bs.carousel
Collapseshow.bs.collapse
shown.bs.collapse
hide.bs.collapse
hidden.bs.collapse
Toastshow.bs.toast
shown.bs.toast
hide.bs.toast
hidden.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:
OptionTypeDefaultDescription
backdropboolean/stringtrueIncludes a backdrop element. Use 'static' for non-dismissible backdrop.
keyboardbooleantrueCloses the component when ESC key is pressed
focusbooleantruePuts focus on the component when initialized
animationbooleantrueApply a CSS fade transition to the component
delaynumber/object0Delay showing and hiding (ms)
placementstring'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
IssueCauseSolution
Components not workingJavaScript not loaded or loaded too earlyLoad Bootstrap JS before closing </body> tag
Tooltips/popovers not showingNot initialized or missing Popper.jsInitialize manually or use bundle version
Modal backdrop issuesMultiple modals or z-index conflictsEnsure proper modal nesting and z-index
Dropdown not closingEvent propagation issuesCheck for JavaScript errors or event handlers
Carousel not slidingMissing slide items or incorrect structureVerify carousel HTML structure
Memory leaksNot disposing instancesCall dispose() when removing elements
Console errorsConflicting jQuery or other librariesCheck 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 null
Verify Event Listeners:
// Check event listeners
        var el = document.getElementById('myButton');
        console.log(el); // Inspect in browser console
        // Check Event Listeners tab in DevTools

Best Practices

JavaScript Integration Best Practices
  • Use the bundled version: bootstrap.bundle.min.js includes 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 components
Bundle 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 trigger
  • new bootstrap.Modal(el) - JS initialization
  • show.bs.modal - Modal show event
  • myModal.dispose() - Clean up instance
  • bootstrap.Modal.getInstance(el) - Get existing instance
  • bootstrap.bundle.min.js - Recommended bundle
Checklist
This content is collapsed by default. It becomes visible when you click the toggle button.