Blog

  • WordPress Tutorial

    WordPress tutorial provides basic and advanced concepts of WordPress. Our WordPress tutorial is designed for beginners and professionals.

    WordPress is an open-source CMS (Content Management System) which is based on PHP and MySQL.

    Our WordPress tutorial includes all topics of WordPress such as installation, creating WordPress site, working on WordPress dashboard, creating and editing posts, pages and comments, working with themes and plugins, WordPress security, how to backup WordPress, optimizing WordPress performance etc.

  • Bootstrap Toasts

    Creating the Toasts with Bootstrap

    The toast component is newly introduced in Bootstrap 4. They are lightweight notifications similar to push notifications that are shown by web browsers on computer screens. They’re built with flexbox, so you can easily align and position them on a web page.

    Additionally, toasts are opt-in for performance reasons, so you must initialize them yourself with toast() method. Also, toasts will automatically hide after 5000 milliseconds (5 seconds), if you do not specify autohide: false option. Now let’s see how to create a toast.

    Step 1: Adding the Toast Markup

    Toasts markups are pretty straightforward. The following example will show you how to create a toast component with a header, body, and a close button.

    Example

    Try this code »

    <div class="toast" id="myToast">
        <div class="toast-header">
            <strong class="me-auto"><i class="bi-gift-fill"></i> We miss you!</strong>
            <small>10 mins ago</small>
            <button type="button" class="btn-close" data-bs-dismiss="toast"></button>
        </div>
        <div class="toast-body">
            It's been a long time since you visited us. We've something special for you. <a href="#">Click here!</a>
        </div>
    </div>

    Step 2: Triggering the Toasts

    Toasts can be triggered via JavaScript — just call the toast() Bootstrap method with the idclass or any CSS selector of the target element in your JavaScript code.

    Example

    jQuery JavaScript

    Try this code »

    <script>
    $(document).ready(function(){
        $("#myBtn").click(function(){
            $("#myToast").toast("show");
        });
    });
    </script>

    — The output of the above example will look something like this:

    Bootstrap Toast

    Changing the Toast’s Color Schemes

    You can use the color and background utility classes to create toasts with different color schemes.

    The following example will create a toast with blue background and white text.

    Example

    Try this code »

    <div class="toast bg-primary text-white fade show">
        <div class="toast-header bg-primary text-white">
            <strong class="me-auto"><i class="bi-gift-fill"></i> We miss you!</strong>
            <small>10 mins ago</small>
            <button type="button" class="btn-close btn-close-white" data-bs-dismiss="toast"></button>
        </div>
        <div class="toast-body">
            It's been a long time since you visited us. We've something special for you. <a href="#" class="text-white">Click here!</a>
        </div>
    </div>

    — The output of the above example will look something like this:

    Bootstrap Toast with Different Color Schemes

    Stacking Toasts Vertically

    You can stack multiple toasts vertically by simply wrapping them in a toast container, which will vertically add some spacing. Let’s take a look at the following example:

    Example

    Try this code »

    <div class="toast-container">
        <div class="toast fade show">
            <div class="toast-header">
                <strong class="me-auto"><i class="bi-globe"></i> Hello, world!</strong>
                <small>just now</small>
                <button type="button" class="btn-close" data-bs-dismiss="toast"></button>
            </div>
            <div class="toast-body">
                This is a basic toast message.
            </div>
        </div>
    
        <div class="toast fade show">
            <div class="toast-header">
                <strong class="me-auto"><i class="bi-globe"></i> Hello, world!</strong>
                <small>5 seconds ago</small>
                <button type="button" class="btn-close" data-bs-dismiss="toast"></button>
            </div>
            <div class="toast-body">
                See? This is another toast message.
            </div>
        </div>
    </div>

    — The output of the above example will look something like this:

    Bootstrap Vertically Stacked Toasts

    Placement of Toasts

    You can place toasts anywhere on your web page using custom CSS positioning. However, the top right, bottom right, or top middle side is recommended for notifications.

    Also, if you only want to show one toast at a time, put the positioning styles inline (i.e. directly on the .toast element). Let’s try out an example and see how it works:

    Example

    Try this code »

    <div class="toast-container" style="position: absolute; top: 10px; right: 10px;">
        <div class="toast fade show">
            <div class="toast-header">
                <strong class="me-auto"><i class="bi-globe"></i> Hello, world!</strong>
                <small>just now</small>
                <button type="button" class="btn-close" data-bs-dismiss="toast"></button>
            </div>
            <div class="toast-body">
                This is a basic toast message.
            </div>
        </div>
    
        <div class="toast fade show">
            <div class="toast-header">
                <strong class="me-auto"><i class="bi-globe"></i> Hello, world!</strong>
                <small>5 seconds ago</small>
                <button type="button" class="btn-close" data-bs-dismiss="toast"></button>
            </div>
            <div class="toast-body">
                See? This is another toast message.
            </div>
        </div>
    </div>

    — The output of the above example will look something like this:

    Bootstrap Toasts Placement

    Options

    There are certain options which can be passed to toast() Bootstrap method to customize the functionality of a toast. Options can be passed via data attributes or JavaScript.

    For setting the toast options via data attributes, just append the option name to data-bs-, such as data-bs-autohide="false"data-bs-delay="3000", etc.

    NameTypeDefault ValueDescription
    animationbooleantrueApply a CSS fade transition to the toast.
    autohidebooleantrueAuto hide the toast.
    delaynumber5000Delay hiding the toast (ms).

    Data attributes provides an easy way for setting the toast options, however JavaScript is the more preferable way as it prevents you from repetitive work. See the passing options examples in the methods section below to know how to set the options for toasts using JavaScript.

    In the following example we’ve set the autohide option to false using the data attribute (line no-1) which prevents the toast from closing automatically.

    Example

    Try this code »

    <div class="toast" id="myToast" data-bs-autohide="false">
        <div class="toast-header">
            <strong class="me-auto"><i class="bi-gift-fill"></i> We miss you!</strong>
            <small>10 mins ago</small>
            <button type="button" class="btn-close" data-bs-dismiss="toast"></button>
        </div>
        <div class="toast-body">
            It's been a long time since you visited us. We've something special for you. <a href="#">Click here!</a>
        </div>
    </div>

    Methods

    These are the standard bootstrap’s toast methods:

    Passing options

    You can additionally pass options to the toast using options object.

    The following example code will prevent the toast from closing automatically.

    Example

    jQuery JavaScript

    Try this code »

    <script>
    $(document).ready(function(){
        $("#myToast").toast({
            autohide: false
        }); 
    });
    </script>

    The following example code will increase the autohide time of toast to 10 seconds.

    Example

    jQuery JavaScript

    Try this code »

    <script>
    $(document).ready(function(){
        $("#myToast").toast({
            delay: 10000
        }); 
    });
    </script>

    show

    This method is used to display the toast.

    Example

    jQuery JavaScript

    Try this code »

    <script>
    $(document).ready(function(){
        $(#myBtn").click(function(){
            $("#myToast").toast("show");
        });
    });
    </script>

    hide

    This method is used to hide toast. You’ve to manually call this method if you set autohide to false.

    Example

    jQuery JavaScript

    Try this code »

    <script>
    $(document).ready(function(){
        $(#myBtn").click(function(){
            $("#myToast").toast("hide");
        });
    });
    </script>

    dispose

    This method hides an element’s toast. The toast will remain on the DOM but won’t show anymore.

    Example

    jQuery JavaScript

    Try this code »

    <script>
    $(document).ready(function(){
        $(#myBtn").click(function(){
            $("#myToast").toast("dispose");
        });
    });
    </script>

    getInstance

    This is a static method which allows you to get the toast instance associated with a DOM element.

    Example

    jQuery JavaScript

    Try this code »

    <script>
    $(document).ready(function(){
        $("#myBtn").click(function(){
            var myToast = bootstrap.Toast.getInstance($("#myToast")[0]);
            console.log(myToast);
            // {_element: div#myToast.toast.fade.show, _config: {…}, _timeout: null, _hasMouseInteraction: false, _hasKeyboardInteraction: false}
        });
    });
    </script>

    getOrCreateInstance

    This is a static method which allows you to get the toast instance associated with a DOM element, or create a new one in case if the toast wasn’t initialized.

    Example

    jQuery JavaScript

    Try this code »

    <script>
    $(document).ready(function(){
        $("#myBtn").click(function(){
            var myToast = bootstrap.Toast.getOrCreateInstance($("#myToast")[0]);
            console.log(myToast);
            // {_element: div#myToast.toast.fade.show, _config: {…}, _timeout: null, _hasMouseInteraction: false, _hasKeyboardInteraction: false}
        });
    });
    </script>

    Tip: Static methods cannot be called on instances of the class (i.e. objects). They’re called on the class itself. The keyword static is used to define a static method for a class.


    Bootstrap’s modal class includes few events for hooking into modal functionality.

    EventDescription
    show.bs.toastThis event fires immediately when the show instance method is called.
    shown.bs.toastThis event is fired when the toast has been made visible to the user. It will wait until the CSS transition process has been fully completed before getting fired.
    hide.bs.toastThis event is fired immediately when the hide instance method has been called.
    hidden.bs.toastThis event is fired when the toast has finished being hidden from the user. It will wait until the CSS transition process has been fully completed before getting fired.

    The following example will display an alert message to the user when the fade out transition of the toast has been fully completed. Let’s try it out and see how it works:

    Example

    jQuery JavaScript

    Try this code »

    <script>
    $(document).ready(function(){
        $("#myToast").on("hidden.bs.toast", function(){
            alert("Toast component has been completely closed.");
        });
    });
    </script>
  • Bootstrap ScrollSpy

    Creating ScrollSpy with Bootstrap

    The Bootstrap scrollspy is a navigation mechanism that automatically highlights the nav links based on the scroll position to indicate the visitor where they are currently on the page.

    The scrollspy will make your web page more elegant and accessible, if you’re using the bookmark links for directing the visitors to the different sections of a page that has a huge amount of content.

    Scrollspy has the following requirements to function properly:

    • It must be used on a Bootstrap nav, or list group component.
    • You must apply the style position: relative; on the element you’re spying on, which is usually the <body> element. But, if you’re spying a <div> or any element other than the <body> be sure to additionally apply a height and overflow-y: scroll; on it.
    • Anchors (<a>) are required and must point to an element with that id.

    Here’s an example of a scrollspy using the list group. Let’s try it out and see how it works:

    Example

    Try this code »

    <body data-bs-spy="scroll" data-bs-offset="15" data-bs-target="#myScrollspy">
        <div class="container">
            <div class="row">
                <div class="col-sm-3" id="myScrollspy">
                    <div class="list-group">
                        <a class="list-group-item list-group-item-action active" href="#section1">Section One</a>
                        <a class="list-group-item list-group-item-action" href="#section2">Section Two</a>
                        <a class="list-group-item list-group-item-action" href="#section3">Section Three</a>
                    </div>
                </div>
                <div class="col-sm-9">
                    <div id="section1">
                        <h2>Section One</h2>
                        <p>This is section one content...</p>
                    </div>
                    <hr>
                    <div id="section2">
                        <h2>Section Two</h2>
                        <p>This is section two content...</p>
                    </div>
                    <hr>
                    <div id="section3">
                        <h2>Section Three</h2>
                        <p>This is section three content...</p>
                    </div>
                </div>
            </div>
        </div>
    </body>

    Creating ScrollSpy via Data Attributes

    You can easily add scrollspy behavior to your navbar via data attributes without writing a single line of JavaScript code. Let’s try out the following example to see how it works:

    Example

    Try this code »

    <body data-bs-spy="scroll" data-bs-offset="60" data-bs-target="#myNavbar">
        <nav id="myNavbar" class="navbar navbar-light bg-light fixed-top">
            <div class="container-fluid">
                <a href="#" class="navbar-brand">Navbar</a>
                <ul class="nav nav-pills">
                    <li class="nav-item">
                        <a href="#section1" class="nav-link">Section 1</a>
                    </li>
                    <li class="nav-item">
                        <a href="#section2" class="nav-link">Section 2</a>
                    </li>
                    <li class="nav-item">
                        <a href="#section3" class="nav-link">Section 3</a>
                    </li>
                    <li class="nav-item dropdown">
                        <a href="#" class="nav-link dropdown-toggle" data-bs-toggle="dropdown">Section 4</a>
                        <div class="dropdown-menu">
                            <a href="#section4dot1" class="dropdown-item">Section 4.1</a>
                            <a href="#section4dot2" class="dropdown-item">Section 4.2</a>
                            <a href="#section4dot3" class="dropdown-item">Section 4.3</a>
                        </div>
                    </li>
                    <li>
                        <a href="#section5" class="nav-link">Section 5</a>
                    </li>
                </ul>
            </div>
        </nav>
        <div class="container">
            <div id="section1">
                <h2>Section 1</h2>
                <p>This is section 1 content...</p>
            </div>
            <hr>
            <div id="section2">
                <h2>Section 2</h2>
                <p>This is section 2 content...</p>
            </div>
            <hr>
            <div id="section3">
                <h2>Section 3</h2>
                <p>This is section 3 content...</p>
            </div>
            <hr>
            <h2>Section 4</h2>
            <p>This is section 4 content</p>
            <div id="section4dot1">
                <h3>Section 4.1</h3>
                <p>This is section 4.1 content...</p>
            </div>
            <div id="section4dot2">
                <h3>Section 4.2</h3>
                <p>This is section 4.2 content...</p>
            </div>
            <div id="section4dot3">
                <h3>Section 4.3</h3>
                <p>This is section 4.3 content...</p>
            </div>
            <hr>
            <div id="section5">
                <h2>Section 5</h2>
                <p>This is section 5 content...</p>
            </div>
        </div>
    </body>

    You might be wondering what this code was all about. Well, let’s go through each part of this scrollspy example code one by one for a better understanding.

    Explanation of Code

    The Bootstrap scrollspy has basically two components — the target (e.g. nav or list group) and the scrollable area to spy on, which is often the <body> section.

    • The data-bs-spy="scroll" attribute (line no-01) is applied to the element you want to spy on, which is simply the <body> element in our case.
    • The data-bs-target attribute is added to the element we’re spying on (i.e. the <body> element) with the ID or class of the parent element of any Bootstrap .nav component, so that nav links can be targeted by the scrollspy for highlighting purpose.
    • The optional data-bs-offset attribute specifies the number of pixels to offset from top when calculating the position of scroll. Adjust the offset value if the targeted links are highlighting too early or too late. The default value is 10 pixels.

    Rest of the thing is self explanatory, such as the .navbar element specifies a Bootstrap navbar, whereas the element <a href="#section1">Section 1</a> (line no-7) creates a bookmark link, the .dropdown element (line no-15) creates a dropdown menu, and so on.


    Creating ScrollSpy via JavaScript

    You may also add scrollspy manually using the JavaScript — just call the scrollspy() Bootstrap method with the id or class selector of the navbar in your JavaScript code.

    Example

    jQuery JavaScript

    Try this code »

    <script>
    $(document).ready(function(){
        $("body").scrollspy({
            target: "#myNavbar"
        }) 
    });
    </script>

    Options

    There are certain options which may be passed to scrollspy() Bootstrap method to customize the functionality of a scrollspy. Options can be passed via data attributes or JavaScript.

    For setting the scrollspy options via data attributes, just append the option name to data-bs-, like data-bs-offset="0"data-bs-method="position", and so on.

    NameTypeDefault ValueDescription
    offsetnumber10Number of pixels to offset from top when calculating position of scroll.
    methodstringautoFinds which section the spied element is in. The value auto will choose the best method get scroll coordinates.Whereas, the value offset will use jQuery offset method to get scroll coordinates, and the value position will use jQuery position method to get scroll coordinates.
    targetstring |
    jQuery object |
    DOM element
    Specifies element to apply Scrollspy plugin.

    Methods

    These are the standard bootstrap’s scrollspy methods:

    Passing options

    You can additionally pass options to the scrollspy using options object.

    The following example will set offset from top when calculating scroll position.

    Example

    jQuery JavaScript

    Try this code »

    <script>
    $(document).ready(function(){
        $("body").scrollspy({
            offset: 70
        }) 
    });
    </script>

    refresh

    You’ll need to call this method when you’re using scrollspy in conjunction with adding or removing elements from the DOM. Let’s try out an example and see how it really works:

    Example

    jQuery JavaScript

    Try this code »

    <script>
    $(document).ready(function(){
        $('[data-spy="scroll"]').each(function(){
            $(this).scrollspy("refresh");
        }); 
    });
    </script>

    dispose

    This method destroys an element’s scrollspy (i.e. removes stored data on the DOM element).

    Example

    jQuery JavaScript

    Try this code »

    <script>
    $(document).ready(function(){
        $("#myBtn").click(function(){
            var myScrollspy = bootstrap.ScrollSpy.getInstance($("#myContent")[0]);
            console.log(myScrollspy);
            // {_element: div#myContent, _scrollElement: div#myContent, _config: {…}, _selector: "#myNavbar .nav-link, #myNavbar .list-group-item, #myNavbar .dropdown-item", _offsets: Array(5), …}
    
            $("#myContent").scrollspy("dispose");
            console.log(myScrollspy);
            // {_element: null, _scrollElement: null, _config: null, _selector: null, _offsets: null, …}
        });
    });
    </script>

    getInstance

    This is a static method which allows you to get the scrollspy instance associated with a DOM element.

    Example

    jQuery JavaScript

    Try this code »

    <script>
    $(document).ready(function(){
        $("#myBtn").click(function(){
            var myScrollspy = bootstrap.ScrollSpy.getInstance($("#myContent")[0]);
            console.log(myScrollspy);
            // {_element: div#myContent, _scrollElement: div#myContent, _config: {…}, _selector: "#myNavbar .nav-link, #myNavbar .list-group-item, #myNavbar .dropdown-item", _offsets: Array(5), …}
        });
    });
    </script>

    getOrCreateInstance

    This is a static method which allows you to get the scrollspy instance associated with a DOM element, or create a new one in case if the scrollspy wasn’t initialized.

    Example

    jQuery JavaScript

    Try this code »

    <script>
    $(document).ready(function(){
        $("#myBtn").click(function(){
            var myScrollspy = bootstrap.ScrollSpy.getOrCreateInstance($("#myContent")[0]);
            console.log(myScrollspy);
            // {_element: div#myContent, _scrollElement: div#myContent, _config: {…}, _selector: "#myNavbar .nav-link, #myNavbar .list-group-item, #myNavbar .dropdown-item", _offsets: Array(5), …}
        });
    });
    </script>

    Events

    Bootstrap’s scrollspy class includes few events for hooking into scrollspy functionality.

    EventDescription
    activate.bs.scrollspyThis event fires whenever a new item becomes activated by the scrollspy.

    The following example displays an alert message when a new item becomes highlighted by the scrollspy. Let’s try it out and see how it actually works.

    Example

    jQuery JavaScript

    Try this code »

    <script>
    $(document).ready(function(){
        $("#myNavbar").on("activate.bs.scrollspy", function(){
            var currentItem = $(".nav li.active > a").text();
            $("#info").empty().html("Currently you are viewing - " + currentItem);
        })
    });
    </script>
  • Bootstrap Typeahead

    Creating Typeaheads with Bootstrap

    The typeahead input fields are very popular in modern web forms. The main purpose of using typeahead is to improve the user experience by supplying hints or a list of possible choices based on the text they’ve entered while filling a form or searching something — like the Google instant search.

    Typeahead functionality also saves time and reduces the number of potential errors, because the user has less likelihood of making a spelling mistake. Typeahead plugin has been dropped from the Bootstrap (v3.0+), in favor of using Twitter typeahead.

    Twitter typeaheads is a fast and fully-featured autocomplete library inspired by twitter.com’s autocomplete search functionality. To create Twitter typeaheads first download typeahead.js from their official page — https://twitter.github.io/typeahead.js/ and include in your project, after that you can turn any text-based <input> element into a typeahead.

    Twitter typeaheads require jQuery 1.9+ to work. Non-jQuery version is not available.

    Creating Twitter Typeahead with Local Dataset

    The following example will show you how to create Twitter typeahead with local dataset.

    Example

    Try this code »

    <script>
    $(document).ready(function(){
        // Defining the local dataset
        var cars = ['Audi', 'BMW', 'Bugatti', 'Ferrari', 'Ford', 'Lamborghini', 'Mercedes Benz', 'Porsche', 'Rolls-Royce', 'Volkswagen'];
        
        // Constructing the suggestion engine
        var cars = new Bloodhound({
            datumTokenizer: Bloodhound.tokenizers.whitespace,
            queryTokenizer: Bloodhound.tokenizers.whitespace,
            local: cars
        });
        
        // Initializing the typeahead
        $('.typeahead').typeahead({
            hint: true,
            highlight: true, /* Enable substring highlighting */
            minLength: 1 /* Specify minimum characters required for showing suggestions */
        },
        {
            name: 'cars',
            source: cars
        });
    });
    </script>

    — The output of the above example will look something like this:

    Twitter Typeahead

    Note: Bloodhound is the typeahead.js suggestion engine. It is very flexible and offers advanced functionalities such as prefetching remote data, fast lookups through intelligent caching using the browser local storage, etc.

    Tip: Set autocomplete="off" for the input box if you want to prevent default browser menus from appearing over the Bootstrap type-ahead dropdown.


    Creating Twitter Typeahead External Dataset

    You can also specify external dataset through a URL pointing to a JSON file containing an array of datums. The individual units that compose datasets are called datums.

    Example

    Try this code »

    <script>
    $(document).ready(function(){
        // Sonstructs the suggestion engine
        var countries = new Bloodhound({
            datumTokenizer: Bloodhound.tokenizers.whitespace,
            queryTokenizer: Bloodhound.tokenizers.whitespace,
            // The url points to a json file that contains an array of country names
            prefetch: 'data/countries.json'
        });
        
        // Initializing the typeahead with remote dataset without highlighting
        $('.typeahead').typeahead(null, {
            name: 'countries',
            source: countries,
            limit: 10 /* Specify max number of suggestions to be displayed */
        });
    });
    </script>
  • Bootstrap Carousel

    Creating Carousels with Bootstrap

    The carousel also known as slideshow or image slider is some of the best way of showcasing the huge amount of contents within a small space on the web pages. It is a dynamic presentation of contents where text and images are made visible or accessible to the user by cycling through several items.

    The following example will show you how to build a simple carousel or slideshow with previous/next controls and indicators using the Bootstrap carousel plugin.

    Example

    Try this code »

    <div id="myCarousel" class="carousel slide" data-bs-ride="carousel">
        <!-- Carousel indicators -->
        <ol class="carousel-indicators">
            <li data-bs-target="#myCarousel" data-bs-slide-to="0" class="active"></li>
            <li data-bs-target="#myCarousel" data-bs-slide-to="1"></li>
            <li data-bs-target="#myCarousel" data-bs-slide-to="2"></li>
        </ol>
    
        <!-- Wrapper for carousel items -->
        <div class="carousel-inner">
            <div class="carousel-item active">
                <img src="images/slide1.png" class="d-block w-100" alt="Slide 1">
            </div>
            <div class="carousel-item">
                <img src="images/slide2.png" class="d-block w-100" alt="Slide 2">
            </div>
            <div class="carousel-item">
                <img src="images/slide3.png" class="d-block w-100" alt="Slide 3">
            </div>
        </div>
    
        <!-- Carousel controls -->
        <a class="carousel-control-prev" href="#myCarousel" data-bs-slide="prev">
            <span class="carousel-control-prev-icon"></span>
        </a>
        <a class="carousel-control-next" href="#myCarousel" data-bs-slide="next">
            <span class="carousel-control-next-icon"></span>
        </a>
    </div>

    — The output of the above example will look something like this:

    Bootstrap Carousel

    Creating Carousel with Captions

    You can also add captions to carousel slides easily with the .carousel-caption element within any .carousel-item. You can optionally use display utility classes to hide captions on smaller viewports.

    Let’s try out the following example to understand how it basically works:

    Example

    Try this code »

    <div id="myCarousel" class="carousel slide" data-bs-ride="carousel">
        <!-- Carousel indicators -->
        <ol class="carousel-indicators">
            <li data-bs-target="#myCarousel" data-bs-slide-to="0" class="active"></li>
            <li data-bs-target="#myCarousel" data-bs-slide-to="1"></li>
            <li data-bs-target="#myCarousel" data-bs-slide-to="2"></li>
        </ol>
        
        <!-- Wrapper for carousel items -->
        <div class="carousel-inner">
            <div class="carousel-item active">
                <img src="images/slide1.png" class="d-block w-100" alt="Slide 1">
                <div class="carousel-caption d-none d-md-block">
                    <h5>First slide label</h5>
                    <p>Some placeholder content for the first slide.</p>
                </div>
            </div>
            <div class="carousel-item">
                <img src="images/slide2.png" class="d-block w-100" alt="Slide 2">
                <div class="carousel-caption d-none d-md-block">
                    <h5>Second slide label</h5>
                    <p>Some placeholder content for the second slide.</p>
                </div>
            </div>
            <div class="carousel-item">
                <img src="images/slide3.png" class="d-block w-100" alt="Slide 3">
                <div class="carousel-caption d-none d-md-block">
                    <h5>Third slide label</h5>
                    <p>Some placeholder content for the third slide.</p>
                </div>
            </div>
        </div>
    
        <!-- Carousel controls -->
        <a class="carousel-control-prev" href="#myCarousel" data-bs-slide="prev">
            <span class="carousel-control-prev-icon"></span>
        </a>
        <a class="carousel-control-next" href="#myCarousel" data-bs-slide="next">
            <span class="carousel-control-next-icon"></span>
        </a>
    </div>

    — The output of the above example will look something like this:

    Bootstrap Carousel with Captions

    Tip: The classes .d-none and .d-md-block on the .carousel-caption elements in the example above makes the carousel captions visible on the medium devices (i.e. viewport width ≥768px), but hide them on the smaller viewports.


    Creating Dark Variant of Carousel

    You can additionally add .carousel-dark to the .carousel to create darker controls, indicators, and captions in case your slides are lighter in color. Let’s check out an example:

    Example

    Try this code »

    <div id="myCarousel" class="carousel carousel-dark slide" data-bs-ride="carousel">
        <!-- Carousel indicators -->
        <ol class="carousel-indicators">
            <li data-bs-target="#myCarousel" data-bs-slide-to="0" class="active"></li>
            <li data-bs-target="#myCarousel" data-bs-slide-to="1"></li>
            <li data-bs-target="#myCarousel" data-bs-slide-to="2"></li>
        </ol>
    
        <!-- Wrapper for carousel items -->
        <div class="carousel-inner">
            <div class="carousel-item active">
                <img src="images/slide1-light.png" class="d-block w-100" alt="Slide 1">
            </div>
            <div class="carousel-item">
                <img src="images/slide2-light.png" class="d-block w-100" alt="Slide 2">
            </div>
            <div class="carousel-item">
                <img src="images/slide3-light.png" class="d-block w-100" alt="Slide 3">
            </div>
        </div>
    
        <!-- Carousel controls -->
        <a class="carousel-control-prev" href="#myCarousel" data-bs-slide="prev">
            <span class="carousel-control-prev-icon"></span>
        </a>
        <a class="carousel-control-next" href="#myCarousel" data-bs-slide="next">
            <span class="carousel-control-next-icon"></span>
        </a>
    </div>

    — The output of the above example will look something like this:

    Bootstrap Carousel Dark

    Check out the snippets section for examples of some beautifully designed Bootstrap carousels.

    You can also add captions such as heading or description text to the individual slides of the carousel, please check out the next example in the following section.


    Activate Carousels via Data Attributes

    With Bootstrap you can create carousels very easily via data attributes without writing a single line of JavaScript code. Let’s take a look at the following example:

    Example

    Try this code »

    <div id="myCarousel" class="carousel slide" data-bs-ride="carousel">
        <!-- Carousel indicators -->
        <ol class="carousel-indicators">
            <li data-bs-target="#myCarousel" data-bs-slide-to="0" class="active"></li>
            <li data-bs-target="#myCarousel" data-bs-slide-to="1"></li>
            <li data-bs-target="#myCarousel" data-bs-slide-to="2"></li>
        </ol>
    
        <!-- Wrapper for carousel items -->
        <div class="carousel-inner">
            <div class="carousel-item active">
                <img src="images/slide1.png" class="d-block w-100" alt="Slide 1">
            </div>
            <div class="carousel-item">
                <img src="images/slide2.png" class="d-block w-100" alt="Slide 2">
            </div>
            <div class="carousel-item">
                <img src="images/slide3.png" class="d-block w-100" alt="Slide 3">
            </div>
        </div>
    
        <!-- Carousel controls -->
        <a class="carousel-control-prev" href="#myCarousel" data-bs-slide="prev">
            <span class="carousel-control-prev-icon"></span>
        </a>
        <a class="carousel-control-next" href="#myCarousel" data-bs-slide="next">
            <span class="carousel-control-next-icon"></span>
        </a>
    </div>

    You might be wondering what this code was all about. Well, let’s go through each part of this carousel example code one by one for a better understanding.

    Explanation of Code

    The Bootstrap carousel generally has three components — carousel indicators (small rectangles), carousel controls (previous and next arrows) and the carousel items or slides.

    • The outermost container of every carousel (i.e. the .carousel element) requires a unique id (in our case id="myCarousel") so that it can be targeted by the carousel indicators (line no-4,5,6) and carousel controls (line no-23,26) to function properly.
    • The data-bs-ride="carousel" attribute of the .carousel element tells the Bootstrap to start animating the carousel immediately when the page load.
    • The data-bs-slide-to attribute (line no-4,5,6) move the slide position to a particular item (index beginning with 0) when clicking on the specific carousel indicator.
    • The slides are specified within the .carousel-inner (line no-10) and the content of each slide is defined within the .carousel-item element that can be text and images.
    • The data-bs-slide attribute on carousel controls (line no-23,26) accepts the keywords prev or next, which alters the slide position relative to its current position.

    Rest of the thing is self-explanatory, for example, the .carousel element specifies the Bootstrap carousel, the .carousel-indicators element indicates how many slides are there in the carousel and which slide is currently active, .carousel-control-prev.carousel-control-next elements defines previous and next controls to move between carousel slides, and so on.

    Tip: It is required to add the class .active to one of the carousel slides (i.e. on the .carousel-item element), otherwise carousel will not be visible.

    Note: The .slide class on the .carousel element adds CSS slide transition animation to the carousel that makes the carousel items slide when showing the new item.


    Activate Carousels via JavaScript

    You may also activate a carousel manually using the JavaScript — just call the carousel() method with the id or class selector of the wrapper element in your JavaScript code.

    Example

    jQuery JavaScript

    Try this code »

    <script>
    $(document).ready(function(){
        $("#myCarousel").carousel();
    });
    </script>

    Tip: Manually activating a carousel via JavaScript can be helpful in a situation when you don’t want your carousel to start sliding or animating at page load.


    Options

    There are certain options which can be passed to carousel() Bootstrap method to customize the functionality of a carousel. Options can be passed via data attributes or JavaScript.

    For setting the modals options via data attributes, just append the option name to data-bs, such as data-bs-interval="3000"data-bs-pause="hover", and so on.

    NameTypeDefault ValueDescription
    intervalnumber5000Specifies the amount of time to delay (in milliseconds) between one slide to another in automatic cycling. If false, carousel will not automatically cycle.
    keyboardbooleantrueSpecifies whether the carousel should react to keyboard events. By default it is true that means if carousel has focus you can go to its previous and next slide using the left and right arrow keys on the keyboard.
    pausestring | boolean‘hover’Pauses the cycling of the carousel when mouse pointer enters the carousel and resumes the cycling when mouse pointer leaves the carousel, by default. If set to false, hovering over the carousel won’t pause it.
    ridestring | booleanfalseAutoplays the carousel after the user manually cycles the first item. If set to 'carousel', autoplays the carousel on load.
    wrapbooleantrueSpecifies whether the carousel should cycle continuously or have hard stops (i.e stop at the last slide).
    touchbooleantrueSpecifies whether the carousel should support left/right swipe interactions on touchscreen devices.

    Data attributes provides an easy way for setting the carousel options, however JavaScript is the more preferable way as it prevents you from repetitive work. See the passing options section below to know how to set the options for carousels using JavaScript.


    Methods

    These are the standard bootstrap’s carousels methods:

    Passing options

    You can additionally pass options to the carousels using options object.

    The following example will turn off auto sliding in the carousel. By default Bootstrap carousel is started playing or sliding automatically when the page loads.

    Example

    jQuery JavaScript

    Try this code »

    <script>
    $(document).ready(function(){
        $("#myCarousel").carousel({
            interval: false
        });
    });
    </script>

    The following example will stop carousel from auto-sliding once the last slide has been reached.

    Example

    jQuery JavaScript

    Try this code »

    <script>
    $(document).ready(function(){
        $("#myCarousel").carousel({
            wrap: false
        });
    });
    </script>

    cycle

    This method start carousel for cycling through the items from left to right.

    Example

    jQuery JavaScript

    Try this code »

    <script>
    $(document).ready(function(){
        $("#myBtn").click(function(){
            $("#myCarousel").carousel("cycle");
        });
    });
    </script>

    pause

    This method stops the carousel from cycling through items.

    Example

    jQuery JavaScript

    Try this code »

    <script>
    $(document).ready(function(){
        $("#myBtn").click(function(){
            $("#myCarousel").carousel("pause");
        });
    });
    </script>

    prev

    This method cycles the carousel to the previous item.

    Example

    jQuery JavaScript

    Try this code »

    <script>
    $(document).ready(function(){
        $("#myBtn").click(function(){
            $("#myCarousel").carousel("prev");
        });
    });
    </script>

    next

    This method cycles the carousel to the next item.

    Example

    jQuery JavaScript

    Try this code »

    <script>
    $(document).ready(function(){
        $("#myBtn").click(function(){
            $("#myCarousel").carousel("next");
        });
    });
    </script>

    nextWhenVisible

    Don’t cycle carousel to next when the page isn’t visible or the carousel or its parent isn’t visible.

    Example

    jQuery JavaScript

    Try this code »

    <script>
    $(document).ready(function(){
        $("#myCarousel").carousel("nextWhenVisible");
    });
    </script>

    to

    This method cycles the carousel to a particular frame (start with 0, similar to an array).

    Example

    jQuery JavaScript

    Try this code »

    <script>
    $(document).ready(function(){
        $("#myBtn").click(function(){
            $("#myCarousel").carousel(2);
        });
    });
    </script>

    dispose

    This method destroys an element’s carousel (i.e. removes stored data on the DOM element).

    Example

    jQuery JavaScript

    Try this code »

    <script>
    $(document).ready(function(){
        $("#myBtn").click(function(){
            var myCarousel = bootstrap.Carousel.getInstance($("#myCarousel")[0]);
            console.log(myCarousel);
            // {_element: div#myCarousel.carousel.slide, _items: Array(3), _interval: 9, _activeElement: div.carousel-item.active, _isPaused: false, …}
    
            $("#myCarousel").carousel("dispose");
            console.log(myCarousel);
            // {_element: null, _items: null, _interval: null, _activeElement: null, _isPaused: null, …}
        });
    });
    </script>

    getInstance

    This is a static method which allows you to get the carousel instance associated with a DOM element.

    Example

    jQuery JavaScript

    Try this code »

    <script>
    $(document).ready(function(){
        $("#myBtn").click(function(){
            var myCarousel = bootstrap.Carousel.getInstance($("#myCarousel")[0]);
            console.log(myCarousel);
            // {_element: div#myCarousel.carousel.slide, _items: Array(3), _interval: 9, _activeElement: div.carousel-item.active, _isPaused: false, …}
        });
    });
    </script>

    getOrCreateInstance

    This is a static method which allows you to get the carousel instance associated with a DOM element, or create a new one in case if the carousel wasn’t initialized.

    Example

    jQuery JavaScript

    Try this code »

    <script>
    $(document).ready(function(){
        $("#myBtn").click(function(){
            var myCarousel = bootstrap.Carousel.getOrCreateInstance($("#myCarousel")[0]);
            console.log(myCarousel);
            // {_element: div#myCarousel.carousel.slide, _items: Array(3), _interval: 9, _activeElement: div.carousel-item.active, _isPaused: false, …}
        });
    });
    </script>

    Events

    Bootstrap’s carousel class includes few events for hooking into carousel functionality.

    EventDescription
    slide.bs.carouselThis event fires immediately when the slide instance method is called.
    slid.bs.carouselThis event is fired when the carousel has completed its slide transition.

    The following example displays an alert message when sliding transition of a carousel item has been fully completed. Let’s try it out and see how it actually works.

    Example

    jQuery JavaScript

    Try this code »

    <script>
    $(document).ready(function(){
        $("#myCarousel").on("slid.bs.carousel", function(){
            alert("The sliding transition of previous carousel item has been fully completed.");
        }); 
    });
    </script>
  • Bootstrap Stateful Buttons

    Controlling Button States

    In the previous section you’ve learnt about the Bootstrap button styling and the modifications as well as how to create button groups and toolbars. With Bootstrap you can do even more with the buttons like controlling the states of buttons, make checkbox and radio inputs behaves like toggle buttons, and so on. In the following section we will discuss them in detail.

    Creating Single Toggle Button

    You can activate toggling (i.e. change the normal state of a button to a push state and vice versa) on a single button by simply adding the data attribute data-bs-toggle="button".

    If you’re pre-toggling a button, you must add the .active class manually.

    Example

    Try this code »

    <button type="button" class="btn btn-outline-primary" data-bs-toggle="button" autocomplete="off">Toggle button</button>
    <button type="button" class="btn btn-outline-primary active" data-bs-toggle="button" autocomplete="off">Active toggle button</button>
    <button type="button" class="btn btn-outline-primary" data-bs-toggle="button" autocomplete="off" disabled>Disabled toggle button</button>

    — The toggle button upon clicking will look something like this:

    Bootstrap Single Toggle Button

    Note: The Mozilla Firefox browser persists the button state across page loads, to prevent this behavior, you may simply set the attribute autocomplete="off" on the form containing the buttons, or directly to the input or button element.


    Creating Checkbox Button Groups

    You can also combine checkboxes to create checkbox style toggling on button groups. Let’s try out the following example to understand how it basically works:

    Example

    Try this code »

    <div class="btn-group">
        <input type="checkbox" class="btn-check" name="options" id="check1" autocomplete="off" checked>
        <label class="btn btn-outline-primary" for="check1">Checkbox 1</label>
        
        <input type="checkbox" class="btn-check" name="options" id="check2" autocomplete="off">
        <label class="btn btn-outline-primary" for="check2">Checkbox 2</label>
        
        <input type="checkbox" class="btn-check" name="options" id="check3" autocomplete="off" checked>
        <label class="btn btn-outline-primary" for="check3">Checkbox 3</label>
    </div>

    — The output of the above example will look something like this:

    Bootstrap Checkbox Button Groups

    Note: Don’t use the .active class to preselect checkbox or radio in button groups, as it only changes the visual appearance to make them look like selected. To actually preselect them you will need to apply the checked attribute on the input element yourself.


    Creating Radio Button Groups

    Similarly, you can create radio buttons style toggling on button groups, like this:

    Example

    Try this code »

    <div class="btn-group">
        <input type="radio" class="btn-check" name="options" id="radio1" autocomplete="off">
        <label class="btn btn-outline-primary" for="radio1">Radio 1</label>
    
        <input type="radio" class="btn-check" name="options" id="radio2" autocomplete="off" checked>
        <label class="btn btn-outline-primary" for="radio2">Radio 2</label>
    
        <input type="radio" class="btn-check" name="options" id="radio3" autocomplete="off">
        <label class="btn btn-outline-primary" for="radio3">Radio 3</label>
    </div>

    — The output of the above example will look something like this:

    Bootstrap Radio Button Groups

    Methods

    These are the standard bootstrap’s buttons methods:

    toggle

    This method toggles push state of the button. It changes the appearance of the button, and makes it look like that it has been activated. You can also enable auto toggling of a button by simply using the data-bs-toggle="button" attribute. Let’s take a look at the following example:

    Example

    jQuery JavaScript

    Try this code »

    <script>
    $(document).ready(function(){
        $(".btn").click(function(){
            $(this).button("toggle");
        });
    });
    </script>

    dispose

    This method destroys an element’s button (i.e. removes stored data on the DOM element).

    Example

    jQuery JavaScript

    Try this code »

    <script>
    $(document).ready(function(){
        $("#disposeBtn").click(function(){
            var myButton = bootstrap.Button.getInstance($("#myButton")[0]);
            console.log(myButton);
            // {_element: button#myButton.btn.btn-outline-primary.active}
    
            myButton.dispose();
            console.log(myButton);
            // {_element: null}
        });
    });
    </script>

    getInstance

    This is a static method which allows you to get the button instance associated with a DOM element.

    Example

    jQuery JavaScript

    Try this code »

    <script>
    $(document).ready(function(){
        $("#getBtn").click(function(){
            var myButton = bootstrap.Button.getInstance($("#myButton")[0]);
            console.log(myButton);
            // {_element: button#myButton.btn.btn-outline-primary.active}
        });
    });
    </script>

    getOrCreateInstance

    This is a static method which allows you to get the button instance associated with a DOM element, or create a new one in case if the button wasn’t initialized.

    Example

    jQuery JavaScript

    Try this code »

    <script>
    $(document).ready(function(){
        $("#getBtn").click(function(){
            var myButton = bootstrap.Button.getOrCreateInstance($("#myButton")[0]);
            console.log(myButton);
        });
    });
    </script>
  • Bootstrap Alerts

    Creating Alert Messages with Bootstrap

    Alert boxes are used quite often to stand out the information that requires immediate attention of the end users such as warning, error or confirmation messages.

    With Bootstrap you can easily create elegant alert messages for various purposes by adding the contextual classes (e.g., .alert-success.alert-warning.alert-info etc.) to the .alert base class. You can also add an optional close button to dismiss any alert.

    Bootstrap provides total 8 different types of alerts. The following example will show you the most commonly used alerts, which are: success, error or danger, warning and info alerts.

    Example

    Try this code »

    <!-- Success Alert -->
    <div class="alert alert-success alert-dismissible fade show">
        <strong>Success!</strong> Your message has been sent successfully.
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
    
    <!-- Error Alert -->
    <div class="alert alert-danger alert-dismissible fade show">
        <strong>Error!</strong> A problem has been occurred while submitting your data.
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
    
    <!-- Warning Alert -->
    <div class="alert alert-warning alert-dismissible fade show">
        <strong>Warning!</strong> There was a problem with your network connection.
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
    
    <!-- Info Alert -->
    <div class="alert alert-info alert-dismissible fade show">
        <strong>Info!</strong> Please read the comments carefully.
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>

    — The output of the above example will look something like this:

    Bootstrap Common Alert Messages

    Here’re the remaining four Bootstrap alerts that can be used for various purposes.

    Example

    Try this code »

    <!-- Primary Alert -->
    <div class="alert alert-primary alert-dismissible fade show">
        <strong>Primary!</strong> This is a simple primary alert box.
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
    
    <!-- Secondary Alert -->
    <div class="alert alert-secondary alert-dismissible fade show">
        <strong>Secondary!</strong> This is a simple secondary alert box.
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
    
    <!-- Dark Alert -->
    <div class="alert alert-dark alert-dismissible fade show">
        <strong>Dark!</strong> This is a simple dark alert box.
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
    
    <!-- Light Alert -->
    <div class="alert alert-light alert-dismissible fade show">
        <strong>Light!</strong> This is a simple light alert box.
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>

    — The output of the above example will look something like this:

    Bootstrap New Alert Boxes

    Tip: The .fade and .show classes on the .alert element enable the fading transition effect while closing the alert boxes. If you don’t want animation just removes these classes. Also, the class .alert-dismissible is required on the .alert element for proper positioning of the .btn-close. If your alert doesn’t have a close button you can skip this class.


    Adding Icons to Bootstrap Alerts

    You can also place icons inside Bootstrap alerts. You can either use Bootstrap icons or third-party icons like Font Awesome. Let’s take a look at the following example:

    Example

    Try this code »

    <!-- Success Alert -->
    <div class="alert alert-success alert-dismissible d-flex align-items-center fade show">
        <i class="bi-check-circle-fill"></i>
        <strong class="mx-2">Success!</strong> Your message has been sent successfully.
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
    
    <!-- Error Alert -->
    <div class="alert alert-danger alert-dismissible d-flex align-items-center fade show">
        <i class="bi-exclamation-octagon-fill"></i>
        <strong class="mx-2">Error!</strong> A problem has been occurred while submitting your data.
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
    
    <!-- Warning Alert -->
    <div class="alert alert-warning alert-dismissible d-flex align-items-center fade show">
        <i class="bi-exclamation-triangle-fill"></i>
        <strong class="mx-2">Warning!</strong> There was a problem with your network connection.
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
    
    <!-- Info Alert -->
    <div class="alert alert-info alert-dismissible d-flex align-items-center fade show">
        <i class="bi-info-circle-fill"></i>
        <strong class="mx-2">Info!</strong> Please read the comments carefully.
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>

    — The output of the above example will look something like this:

    Bootstrap Alert Messages with Icons

    Additional Content inside Alerts

    You can also place additional HTML elements like headings, paragraphs and dividers inside an alert. To manage spacing between the elements you can use margin utility classes, as here:

    Example

    Try this code »

    <div class="alert alert-danger alert-dismissible fade show">
        <h4 class="alert-heading"><i class="bi-exclamation-octagon-fill"></i> Oops! Something went wrong.</h4>
        <p>Please enter a valid value in all the required fields before proceeding. If you need any help just place the mouse pointer above info icon next to the form field.</p>
        <hr>
        <p class="mb-0">Once you have filled all the details, click on the 'Next' button to continue.</p>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>

    — The output of the above example will look something like this:

    Bootstrap Alerts with Additional Content

    Matching Links Color inside Alerts

    You can apply the utility class .alert-link to the links inside any alert boxes to quickly create matching colored links, as shown in the example below:

    Example

    Try this code »

    <div class="alert alert-warning alert-dismissible fade show">
        <strong>Warning!</strong> A simple warning alert with <a href="#" class="alert-link">an example link</a>.
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>

    — The output of the above example will look something like this:

    Links inside Bootstrap Alert Messages

    Similarly, you can match links inside other alert boxes. Let’s try out the following example:

    Example

    Try this code »

    <!-- Success Alert -->
    <div class="alert alert-success alert-dismissible fade show">
        <strong>Success!</strong> A simple success alert with <a href="#" class="alert-link">an example link</a>.
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
    
    <!-- Error Alert -->
    <div class="alert alert-danger alert-dismissible fade show">
        <strong>Error!</strong> A simple danger alert with <a href="#" class="alert-link">an example link</a>.
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
    
    <!-- Warning Alert -->
    <div class="alert alert-warning alert-dismissible fade show">
        <strong>Warning!</strong> A simple warning alert with <a href="#" class="alert-link">an example link</a>.
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
    
    <!-- Info Alert -->
    <div class="alert alert-info alert-dismissible fade show">
        <strong>Info!</strong> A simple info alert with <a href="#" class="alert-link">an example link</a>.
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
    
    <!-- Primary Alert -->
    <div class="alert alert-primary alert-dismissible fade show">
        <strong>Primary!</strong> A simple primary alert with <a href="#" class="alert-link">an example link</a>.
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
    
    <!-- Secondary Alert -->
    <div class="alert alert-secondary alert-dismissible fade show">
        <strong>Secondary!</strong> A simple secondary alert with <a href="#" class="alert-link">an example link</a>.
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
    
    <!-- Dark Alert -->
    <div class="alert alert-dark alert-dismissible fade show">
        <strong>Dark!</strong> A simple dark alert with <a href="#" class="alert-link">an example link</a>.
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
    
    <!-- Light Alert -->
    <div class="alert alert-light alert-dismissible fade show">
        <strong>Light!</strong> A simple light alert with <a href="#" class="alert-link">an example link</a>.
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>

    Closing Alerts via Data Attribute

    Data attributes provides a simple and easy way to add close functionality to the alert boxes.

    Just add the data-bs-dismiss="alert" to the close button and it will automatically enable the dismissal of the containing alert message box. Also, add the class .alert-dismissible to the .alert element for proper positioning of the .btn-close button.

    Example

    Try this code »

    <div class="alert alert-info alert-dismissible fade show">
        <strong>Note!</strong> This is a simple example of dismissible alert.
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>

    Use the <button> element for creating the close button for consistent behavior across all devices.


    Closing Alerts via JavaScript

    You may also dismiss an alert via JavaScript. Let’s try out an example and see how it works:

    Example

    jQuery JavaScript

    Try this code »

    <script>
    $(document).ready(function(){
        $("#myBtn").click(function(){
            $("#myAlert").alert("close");
        });
    });
    </script>

    Methods

    These are the standard bootstrap’s alerts methods:

    close

    This method closes an alert by removing it from the DOM. If the .fade and .show classes are present on the element, the alert will fade out before it is removed.

    Example

    jQuery JavaScript

    Try this code »

    <script>
    $(document).ready(function(){
        $("#myBtn").click(function(){
            $("#myAlert").alert("close");
        });
    });
    </script>

    dispose

    This method destroys an element’s alert (i.e. removes stored data on the DOM element).

    Example

    jQuery JavaScript

    Try this code »

    <script>
    $(document).ready(function(){
        $("#myBtn").click(function(){
            $("#myAlert").alert("dispose");
        });
    });
    </script>

    getInstance

    This is a static method which allows you to get the alert instance associated with a DOM element.

    Example

    jQuery JavaScript

    Try this code »

    <script>
    $(document).ready(function(){
        // Create alert instance
        $("#myAlert").alert();
    
        // Get alert instance on button click
        $("#myBtn").click(function(){
            var myAlert = bootstrap.Alert.getInstance($("#myAlert")[0]);
            console.log(myAlert);
            // {_element: div#myAlert.alert.alert-info.alert-dismissible.fade.show}
        });
    });
    </script>

    getOrCreateInstance

    This is a static method which allows you to get the alert instance associated with a DOM element, or create a new one in case if the alert wasn’t initialized.

    Example

    jQuery JavaScript

    Try this code »

    <script>
    $(document).ready(function(){
        $("#myBtn").click(function(){
            var myAlert = bootstrap.Alert.getOrCreateInstance($("#myAlert")[0]);
            console.log(myAlert);
            // {_element: div#myAlert.alert.alert-info.alert-dismissible.fade.show}
        });
    });
    </script>

    Events

    Bootstrap’s alert class includes few events for hooking into alert functionality.

    EventDescription
    close.bs.alertThis event fires immediately when the close instance method is called.
    closed.bs.alertThis event is fired when the alert has been closed and CSS transitions have completed.

    The following example displays an alert message to the user when fade out transition of an alert message box has been fully completed.

    Example

    jQuery JavaScript

    Try this code »

    <script>
    $(document).ready(function(){
        $("#myAlert").on("closed.bs.alert", function(){
            alert("Alert message box has been closed.");
        });
    });
    </script>
  • Bootstrap Popovers

    Creating Popovers with Bootstrap

    Popover is a small overlay of content that is used to display secondary information of any element when it is clicked by a user, like those on the iPad.

    Step 1: Adding the Popover Markup

    To create a popover, you need to add the data-bs-toggle="popover" attribute to an element. Whereas, popover’s title and its content that would display upon trigger or activation can be specified using the title and data-bs-content attribute respectively.

    Here is the standard markup for adding a popover to a button.

    <button type=”button” data-bs-toggle=”popover” title=”Popover title” data-bs-content=”Here’s some amazing content.”>Click to toggle popover</button>

    Similarly, you can add popovers to the other elements such as links, icons, etc.

    Note: For performance reasons the popovers data-apis are opt in like tooltips, means to use popovers you must initialize them yourself. Also, popovers with zero-length title and content values are never displayed, as well as triggering popovers on hidden elements will not work.

    Step 2: Enabling the Popovers

    Popovers can be triggered via JavaScript — just call the popover() Bootstrap method with the idclass or any CSS selector of the required element in your JavaScript code.

    You can either initialize popovers individually or all in one go. The following example code will initialize all popovers on the page by selecting them by their data-bs-toggle attribute.

    Example

    jQuery JavaScript

    Try this code »

    <script>
    $(document).ready(function(){
        $('[data-bs-toggle="popover"]').popover();  
    });
    </script>

    — The output of the above example will look something like this:

    Bootstrap Popover

    Setting the Directions of Popovers

    You can set popovers to appear on top, right, bottom and left sides of an element.

    Positioning of Popovers via Data Attributes

    The following example will show you how to set the direction of popovers via data attributes.

    Example

    Try this code »

    <button type="button" class="btn btn-secondary" data-bs-toggle="popover" data-bs-placement="top" title="Popover title" data-bs-content="Popover on top">Popover on top</button>
    <button type="button" class="btn btn-secondary" data-bs-toggle="popover" data-bs-placement="right" title="Popover title" data-bs-content="Popover on right.">Popover on right</button>
    <button type="button" class="btn btn-secondary" data-bs-toggle="popover" data-bs-placement="bottom" title="Popover title" data-bs-content="Popover on bottom.">Popover on bottom</button>
    <button type="button" class="btn btn-secondary" data-bs-toggle="popover" data-bs-placement="left" title="Popover title" data-bs-content="Popover on left.">Popover on left</button>

    Positioning of Popovers via JavaScript

    The following example will show you how to set the direction of popovers via JavaScript.

    Example

    jQuery JavaScript

    Try this code »

    <script>
    $(document).ready(function(){
        $("#popTop").popover({placement : "top"});
        $("#popRight").popover({placement : "right"});
        $("#popBottom").popover({placement : "bottom"});
        $("#popLeft").popover({ placement : "left"});
    });
    </script>

    Hiding the Popovers on Next Click

    By default popovers are not hiding until you click the trigger element once again. You can use the focus trigger to hide the popovers when the user makes the next click.

    Example

    Try this code »

    <a href="#" class="btn btn-primary" tabindex="0" data-bs-toggle="popover" data-bs-trigger="focus" title="Popover title" data-bs-content="Here's some amazing content.">Dismissible popover</a>

    Note: To make this feature work properly across the browsers, you must use the <a> tag, not the <button> tag, and you also must include a tabindex attribute.


    Options

    There are certain options which may be passed to popover() Bootstrap method to customize the functionality of the popover plugin.

    NameTypeDefault ValueDescription
    animationbooleantrueApply a CSS fade transition to the popover.
    containerstring | element | falsefalseAppends the popover to a specific element.Specify container: 'body' to avoid rendering problems in more complex components (like input groups, button groups, etc.)
    contentstring | element | functionSets default content value if data-bs-content attribute isn’t present.
    delaynumber | object0Time to delay in showing and hiding the popover (ms) — does not apply to manual trigger type.If a number is supplied, delay is applied to both hide/showObject structure is: delay: { "show": 500, "hide": 100 }
    htmlbooleanfalseInsert HTML into the popover.If falseinnerText property will be used to insert content into the DOM.Use simple text if you’re worried about XSS attacks.
    placementstring | function‘right’Sets the position of the popover — auto | top | bottom | left | right.When auto value is specified, it will dynamically reorient the popover.
    selectorstring | falsefalseIf a selector is provided, popover objects will be attached to the specified targets.This is normally used to apply popovers to dynamically added DOM elements.
    templatestring'<div class="popover"><div class="popover-arrow"></div><h3 class="popover-header"></h3><div class="popover-body"></div></div>'Base HTML to use when creating the popover.The popover’s title will be inserted into the .popover-header element.The popover’s content will be inserted into the .popover-body element.The .popover-arrow element will become the popover’s arrow.The outermost wrapper element should have the .popover class.
    titlestring | element | functionSets the default title value if title attribute isn’t present.
    triggerstring‘click’Specify how popover is triggered — click | hover | focus | manual. You can pass multiple triggers; separated with a space.The value manual indicates that the popover will be triggered programmatically via the .show().hide() and .toggle() methods; this value cannot be combined with any other trigger.
    fallbackPlacementsarray[‘top’, ‘right’, ‘bottom’, ‘left’]Allows you to specify which placement Popper will use on fallback.
    boundarystring | element‘clippingParents’Overflow constraint boundary of the popover (applies only to Popper’s preventOverflow modifier). It can also accept an HTMLElement reference (via JavaScript only).
    customClassstring | functionAdd classes to the popover when it is shown. Please note that these classes will be added in addition to any classes specified in the template. To add multiple classes, separate them with spaces like: 'class1 class2'.You can also pass a function that should return a single string containing additional class names.
    sanitizebooleantrueEnable or disable the sanitization. If activated 'template''content' and 'title' options will be sanitized.
    allowListobjectDefault valueObject which contains allowed attributes and tags.
    sanitizeFnnull | functionnullAllows you to specify your own sanitize function.
    offsetarray | string | function[0, 8]Offset of the popover relative to its target. You can also pass a string in data attributes with comma separated values like: data-bs-offset="10,20"
    popperConfignull | object | functionnullAllows you to change Bootstrap’s default Popper config, see Popper’s configuration.

    You can set these options either through the use of data attributes or JavaScript. For setting the popovers options via data attributes, just append the option name to data-bs- along with the correct value, like data-bs-animation="false"data-bs-placement="top" etc.

    Also, when passing the options via data attributes make sure to change the case type of the option name from camelCase to kebab-case. For example, instead of using data-bs-customClass="my-class", use data-bs-custom-class="my-class".

    However, JavaScript is the preferred way of setting these options as it prevents you from repetitive work. See the passing options section below to know how to set the options for popovers via JavaScript.


    Methods

    These are the standard Bootstrap’s popover methods:

    Passing options

    You can additionally pass options to the popovers using options object.

    The following example will set the title text for the popovers dynamically, if the value of the title attribute is omitted or missing from the selected elements:

    Example

    jQuery JavaScript

    Try this code »

    <script>
    $(document).ready(function(){
        $("#myPopover").popover({
            title : "Default popover title"
        });
    });
    </script>

    The following example will show you how to place the HTML content inside a popover:

    Example

    jQuery JavaScript

    Try this code »

    <script>
    $(document).ready(function(){
        $("#myPopover").popover({
            title: '<h4 class="custom-title"><i class="bi-info-circle-fill"></i> Popover info</h4>',
            content: '<p>This is a <em>simple example</em> demonstrating how to insert HTML code inside <strong>Bootstrap popover</strong>.</p>',
            html: true
        }); 
    });
    </script>

    The following example will show you how to control the timing of showing and hiding the popover using the popover’s delay option dynamically via JavaScript.

    Example

    jQuery JavaScript

    Try this code »

    <script>
    $(document).ready(function(){
        // Show and hide popover with same speed
        $("#tinyPopover").popover({
            delay: 100
        });
        
        // Show and hide popover with different speed
        $("#largePopover").popover({
            delay: {show: 0, hide: 2000}
        }); 
    });
    </script>

    The following example will show you how to create your own custom template for Bootstrap popovers instead of using the default one dynamically via JavaScript.

    Example

    jQuery JavaScript

    Try this code »

    <script>
    $(document).ready(function(){
        $('[data-bs-toggle="popover"]').popover({
            template: '<div class="popover"><div class="popover-arrow"></div><h3 class="popover-header"></h3><div class="popover-body"></div><div class="popover-footer"><a class="btn btn-secondary btn-sm close">Close</a></div></div>'
        });
    
        // Close popover on button click
        $(document).on("click", ".popover .close" , function(){
            $(this).parents(".popover").popover("hide");
        });
    });
    </script>

    The following example will insert the dynamically generated HTML code of the popover at the end of the #wrapper element instead of the default <body> element.

    Example

    jQuery JavaScript

    Try this code »

    <script>
    $(document).ready(function(){
        // Append popover HTML to wrapper element
        $("#myPopover").popover({
            container: "#wrapper"
        }); 
    });
    </script>

    Note: Overriding the popover’s default container option value does not produce any visible difference on page. To see the actual result you need to inspect the DOM. Press Ctrl+Shift+I (Windows / Linux) or Cmd+Opt+I (Mac) to open Developer tools or DOM Inspector.

    Similarly, you can set other options for the popovers. Let’s check out the other methods of the Bootstrap popover plugin.

    show

    This method reveals an element’s popover. This is considered a “manual” triggering of the popover.

    Example

    jQuery JavaScript

    Try this code »

    <script>
    $(document).ready(function(){
        $("#myBtn").click(function(){
            $("#myPopover").popover("show");
        }); 
    });
    </script>

    hide

    This method hides an element’s popover. This is considered a “manual” triggering of the popover.

    Example

    jQuery JavaScript

    Try this code »

    <script>
    $(document).ready(function(){
        $("#myBtn").click(function(){
            $("#myPopover").popover("hide");
        }); 
    });
    </script>

    toggle

    This method toggles an element’s popover. This is considered a “manual” triggering of the popover.

    Example

    jQuery JavaScript

    Try this code »

    <script>
    $(document).ready(function(){
        $("#myBtn").click(function(){
            $("#myPopover").popover("toggle");
        }); 
    });
    </script>

    dispose

    This method hides and destroys an element’s popover (i.e. removes stored data on the DOM element).

    Example

    jQuery JavaScript

    Try this code »

    <script>
    $(document).ready(function(){
        $("#myBtn").click(function(){
            $("#myPopover").popover("dispose");
        }); 
    });
    </script>

    enable

    This method gives an element’s popover the ability to be shown. Popovers are enabled by default.

    Example

    jQuery JavaScript

    Try this code »

    <script>
    $(document).ready(function(){
        $("#myBtn").click(function(){
            $("#myPopover").popover("enable");
        }); 
    });
    </script>

    disable

    This method removes the ability for an element’s popover to be shown. The popover will only be able to be shown if it is re-enabled.

    Example

    jQuery JavaScript

    Try this code »

    <script>
    $(document).ready(function(){
        $("#myBtn").click(function(){
            $("#myPopover").popover("disable");
        }); 
    });
    </script>

    toggleEnabled

    This method toggles the ability for an element’s popover to be shown or hidden.

    Example

    jQuery JavaScript

    Try this code »

    <script>
    $(document).ready(function(){
        $("#myBtn").click(function(){
            $("#myPopover").popover("toggleEnabled");
        }); 
    });
    </script>

    update

    This method updates the position of an element’s popover.

    Example

    jQuery JavaScript

    Try this code »

    <script>
    $(document).ready(function(){
        $("#myBtn").click(function(){
            $("#myPopover").popover("update");
        }); 
    });
    </script>

    getInstance

    This is a static method which allows you to get the popover instance associated with a DOM element.

    Example

    jQuery JavaScript

    Try this code »

    <script>
    $(document).ready(function(){
        // Trigger the popover
        $("#myPopover").popover();
        
        // Get popover instance on button click
        $("#myBtn").click(function(){      	
            var myPopover = bootstrap.Popover.getInstance($("#myPopover")[0]);
            console.log(myPopover);
            // {_element: button#myPopover.btn.btn-primary.btn-lg, _isEnabled: true, _timeout: 0, _hoverState: null, _activeTrigger: {…}, …}
        });
    });
    </script>

    getOrCreateInstance

    This is a static method which allows you to get the popover instance associated with a DOM element, or create a new one in case if the popover wasn’t initialized.

    Example

    jQuery JavaScript

    Try this code »

    <script>
    $(document).ready(function(){
        // Get or create popover instance on button click
        $("#myBtn").click(function(){
            var myPopover = bootstrap.Popover.getOrCreateInstance($("#myPopover")[0]);
            console.log(myPopover);
            // {_element: button#myPopover.btn.btn-primary.btn-lg, _isEnabled: true, _timeout: 0, _hoverState: "", _activeTrigger: {…}, …}
        });
    });
    </script>

    Events

    Bootstrap’s popover class includes few events for hooking into popover functionality.

    EventDescription
    show.bs.popoverThis event fires immediately when the show instance method is called.
    shown.bs.popoverThis event is fired when the popover has been made visible to the user. It will wait until the CSS transition process has been fully completed before getting fired.
    hide.bs.popoverThis event is fired immediately when the hide instance method has been called.
    hidden.bs.popoverThis event is fired when the popover has finished being hidden from the user. It will wait until the CSS transition process has been fully completed before getting fired.
    inserted.bs.popoverThis event is fired after the show.bs.popover event when the popover template has been added to the DOM.

    The following example will display an alert message to the user when the fade out transition of the popover has been fully completed.

    Example

    jQuery JavaScript

    Try this code »

    <script>
    $(document).ready(function(){
        // Initialize popover
        $("#myPopover").popover();
    
        // Show alert when the popover has finished being hidden 
        $("#myPopover").on("hidden.bs.popover", function(){
            alert("Popover has been completely closed.");
        });
    });
    </script>
  • Bootstrap Tooltips

    Creating the Tooltips with Bootstrap

    A tooltip is a small pop up that appears when user places the mouse pointer over an element such as link or buttons to provide hint or information about the element being hovered.

    Tooltips can be very helpful for the new visitors of your website because they enable the user to know the purpose of icons and links by placing the mouse pointer over them.

    Step 1: Adding the Tooltip Markup

    To create a tooltip, you need to add the data-bs-toggle="tooltip" attribute to an element. Tolltip text that would display on hover can be specified using the title attribute.

    Here is the standard markup for adding a tolltip to a hyperlink.

    <a href=”#” data-bs-toggle=”tooltip” title=”Some text”>Hover over me</a>

    Similarly, you can add tooltips to the other elements such as buttons, icons, etc.

    Step 2: Enabling the Tooltips

    Tooltips can be enabled via JavaScript — just call the tooltip() Bootstrap method with the idclass or any CSS selector of the target element in your JavaScript code.

    You can either initialize tooltips individually or all in one go. The following jQuery code will initialize all tooltips on the page by selecting them by their data-bs-toggle attribute.

    Example

    jQuery JavaScript

    Try this code »

    <script>
    $(document).ready(function(){
        $('[data-bs-toggle="tooltip"]').tooltip();   
    });
    </script>

    — The output of the above example will look something like this:

    Bootstrap Tooltip

    Note: For performance reasons the tooltip data-apis are opt in, means to use tooltips you must initialize them yourself. Also, tooltips with zero-length titles are never displayed, as well as triggering tooltips on hidden elements will not work.

    Tip: Tooltips for .disabled or disabled elements must be triggered on a wrapper element. Also, when tooltips are triggered from hyperlinks that span multiple lines, it will be centered. You can use white-space: nowrap; on those hyperlinks to avoid this behavior.


    Setting the Directions of Tooltips

    You can set tooltips to appear on top, right, bottom and left sides of an element.

    Positioning of Tooltips via Data Attributes

    The following example will show you how to set the direction of tooltips via data attributes.

    Example

    Try this code »

    <a href="#" data-bs-toggle="tooltip" data-bs-placement="top" title="Tooltip on top">Tooltip on top</a>
    <a href="#" data-bs-toggle="tooltip" data-bs-placement="right" title="Tooltip on right">Tooltip on right</a>
    <a href="#" data-bs-toggle="tooltip" data-bs-placement="bottom" title="Tooltip on bottom">Tooltip on bottom</a>
    <a href="#" data-bs-toggle="tooltip" data-bs-placement="left" title="Tooltip on left">Tooltip on left</a>

    Positioning of Tooltips via JavaScript

    The following example will show you how to set the direction of tooltips via JavaScript.

    Example

    jQuery JavaScript

    Try this code »

    <script>
    $(document).ready(function(){
        $("#tipTop").tooltip({ placement : "top" });
        $("#tipRight").tooltip({ placement : "right" });
        $("#tipBottom").tooltip({ placement : "bottom" });
        $("#tipLeft").tooltip({ placement : "left" });
    });
    </script>

    Options

    There are certain options which may be passed to tooltip() Bootstrap method to customize the functionality of the tooltip plugin.

    NameTypeDefault ValueDescription
    animationbooleantrueApply a CSS fade transition to the tooltip.
    containerstring | element | falsefalseAppends the tooltip to a specific element.Specify container: 'body' to avoid rendering problems in more complex components (like input groups, button groups, etc.)
    delaynumber | object0Time to delay in showing and hiding the tooltip (ms) — does not apply to manual trigger type.If a number is supplied, delay is applied to both hide/showObject structure is: delay: { "show": 500, "hide": 100 }
    htmlbooleanfalseInsert HTML into the tooltip.If true, HTML tags in the tooltip’s title will be rendered in the tooltip. If false, innerText property will be used to insert content into the DOM.Use simple text if you’re worried about XSS attacks.
    placementstring | function‘top’Sets the position of the tooltip — auto | top | bottom | left | right.When auto value is specified, it will dynamically reorient the tooltip.
    selectorstring | falsefalseIf a selector is provided, tooltip objects will be attached to the specified targets.This is normally used to apply tooltips to dynamically added DOM elements.
    templatestring'<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>'Base HTML to use when creating the tooltip.The tooltip’s title will be inserted into the .tooltip-inner element.The .tooltip-arrow element will become the tooltip’s arrow.The outermost wrapper element should have the .tooltip class.
    titlestring | element | functionSets the default title value if title attribute isn’t present.
    triggerstring‘hover focus’Specify how tooltip is triggered — click | hover | focus | manual. You can pass multiple triggers; separated with a space.The value manual indicates that the tooltip will be triggered programmatically via the .show().hide() and .toggle() methods; this value cannot be combined with any other trigger.
    fallbackPlacementsarray[‘top’, ‘right’, ‘bottom’, ‘left’]Allows you to specify which placement Popper will use on fallback.
    boundarystring | element‘clippingParents’Overflow constraint boundary of the tooltip (applies only to Popper’s preventOverflow modifier). It can also accept an HTMLElement reference (via JavaScript only).
    customClassstring | functionAdd classes to the tooltip when it is shown. Please note that these classes will be added in addition to any classes specified in the template. To add multiple classes, separate them with spaces like: 'class1 class2'.You can also pass a function that should return a single string containing additional class names.
    sanitizebooleantrueEnable or disable the sanitization. If activated 'template' and 'title' options will be sanitized.
    allowListobjectDefault valueObject which contains allowed attributes and tags.
    sanitizeFnnull | functionnullAllows you to specify your own sanitize function.
    offsetarray | string | function[0, 0]Offset of the tooltip relative to its target. You can also pass a string in data attributes with comma separated values like: data-bs-offset="10,20"
    popperConfignull | object | functionnullAllows you to change Bootstrap’s default Popper config, see Popper’s configuration.

    You can set these options either through the use of data attributes or JavaScript. For setting the tooltips options via data attributes, just append the option name to data-bs- along with the correct value, like data-bs-animation="false"data-bs-placement="bottom" etc.

    Also, when passing the options via data attributes make sure to change the case type of the option name from camelCase to kebab-case. For example, instead of using data-bs-customClass="my-class", use data-bs-custom-class="my-class".

    However, JavaScript is the preferred way of setting these options as it prevents you from repetitive work. See the passing options section below to know how to set the options for tooltips via JavaScript.


    Methods

    These are the standard Bootstrap’s tooltip methods:

    Passing options

    You can additionally pass options to the tooltips using options object.

    The following example will set the title text for the tooltips dynamically, if the value of the title attribute is omitted or missing from the selected elements:

    Example

    jQuery JavaScript

    Try this code »

    <script>
    $(document).ready(function(){
        $("#myTooltip").tooltip({
            title : "It looks like title attribute is not present."
        });
    });
    </script>

    The following example will show you how to place the HTML content inside a tooltip:

    Example

    jQuery JavaScript

    Try this code »

    <script>
    $(document).ready(function(){
        $("#myTooltip").tooltip({
            title: "<h4><img src='images/smiley.png' width='30' alt='Smiley'> Hello, <b>I'm</b> <i>Smiley!</i></h4>",  
            html: true
        }); 
    });
    </script>

    The following example will show you how to control the timing of showing and hiding the tooltip using the tooltip’s delay option dynamically via JavaScript.

    Example

    jQuery JavaScript

    Try this code »

    <script>
    $(document).ready(function(){
        // Show and hide tooltip with same speed
        $("#tinyTooltip").tooltip({
            delay: 100
        });
        
        // Show and hide tooltip with different speed
        $("#largeTooltip").tooltip({
            delay: {show: 0, hide: 2000}
        }); 
    });
    </script>

    The following example will show you how to create your own custom template for Bootstrap tooltips instead of using the default one dynamically via JavaScript.

    Example

    jQuery JavaScript

    Try this code »

    <script>
    $(document).ready(function(){
        $("#myTooltip").tooltip({
            template: '<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-head"><h3><i class="bi-info-circle"></i> Important Info</h3></div><div class="tooltip-inner"></div>'
        });
    });
    </script>

    The following example will insert the dynamically generated HTML code of the tooltip at the end of the #wrapper element instead of the default <body> element.

    Example

    jQuery JavaScript

    Try this code »

    <script>
    $(document).ready(function(){
        // Append tooltip HTML to wrapper element
        $("#myTooltip").tooltip({
            container: "#wrapper"
        }); 
    });
    </script>

    Note: Overriding the tooltip’s default container option value does not produce any visible difference on page. To see the actual result you need to inspect the DOM. Press Ctrl+Shift+I (Windows / Linux) or Cmd+Opt+I (Mac) to open Developer tools or DOM Inspector.

    Similarly, you can set other options for the tooltips. Let’s check out the other methods of the Bootstrap tooltip plugin.

    show

    This method reveals an element’s tooltip. This is considered a “manual” triggering of the tooltip.

    Example

    jQuery JavaScript

    Try this code »

    <script>
    $(document).ready(function(){
        $("#myBtn").click(function(){
            $("#myTooltip").tooltip("show");
        }); 
    });
    </script>

    hide

    This method hides an element’s tooltip. This is considered a “manual” triggering of the tooltip.

    Example

    jQuery JavaScript

    Try this code »

    <script>
    $(document).ready(function(){
        $("#myBtn").click(function(){
            $("#myTooltip").tooltip("hide");
        }); 
    });
    </script>

    toggle

    This method toggles an element’s tooltip. This is considered a “manual” triggering of the tooltip.

    Example

    jQuery JavaScript

    Try this code »

    <script>
    $(document).ready(function(){
        $("#myBtn").click(function(){
            $("#myTooltip").tooltip("toggle");
        }); 
    });
    </script>

    dispose

    This method hides and destroys an element’s tooltip (i.e. removes stored data on the DOM element).

    Example

    jQuery JavaScript

    Try this code »

    <script>
    $(document).ready(function(){
        $("#myBtn").click(function(){
            $("#myTooltip").tooltip("dispose");
        }); 
    });
    </script>

    enable

    This method gives an element’s tooltip the ability to be shown. Tooltips are enabled by default.

    Example

    jQuery JavaScript

    Try this code »

    <script>
    $(document).ready(function(){
        $("#myBtn").click(function(){
            $("#myTooltip").tooltip("enable");
        }); 
    });
    </script>

    disable

    This method removes the ability for an element’s tooltip to be shown. The tooltip will only be able to be shown if it is re-enabled.

    Example

    jQuery JavaScript

    Try this code »

    <script>
    $(document).ready(function(){
        $("#myBtn").click(function(){
            $("#myTooltip").tooltip("disable");
        }); 
    });
    </script>

    toggleEnabled

    This method toggles the ability for an element’s tooltip to be shown or hidden.

    Example

    jQuery JavaScript

    Try this code »

    <script>
    $(document).ready(function(){
        $("#myBtn").click(function(){
            $("#myTooltip").tooltip("toggleEnabled");
        }); 
    });
    </script>

    update

    This method updates the position of an element’s tooltip.

    Example

    jQuery JavaScript

    Try this code »

    <script>
    $(document).ready(function(){
        $("#myBtn").click(function(){
            $("#myTooltip").tooltip("update");
        }); 
    });
    </script>

    getInstance

    This is a static method which allows you to get the tooltip instance associated with a DOM element.

    Example

    jQuery JavaScript

    Try this code »

    <script>
    $(document).ready(function(){
        // Trigger the tooltip
        $("#myTooltip").tooltip();
        
        // Get tooltip instance on button click
        $("#myBtn").click(function(){      	
            var myTooltip = bootstrap.Tooltip.getInstance($("#myTooltip")[0]);
            console.log(myTooltip);
            // {_element: a#myTooltip, _isEnabled: true, _timeout: 0, _hoverState: "", _activeTrigger: {…}, …}
        });
    });
    </script>

    getOrCreateInstance

    This is a static method which allows you to get the tooltip instance associated with a DOM element, or create a new one in case if the tooltip wasn’t initialized.

    Example

    jQuery JavaScript

    Try this code »

    <script>
    $(document).ready(function(){
        // Get or create tooltip instance on button click
        $("#myBtn").click(function(){
            var myTooltip = bootstrap.Tooltip.getOrCreateInstance($("#myTooltip")[0]);
            console.log(myTooltip);
            // {_element: a#myTooltip, _isEnabled: true, _timeout: 0, _hoverState: "", _activeTrigger: {…}, …}
        });
    });
    </script>

    Events

    Bootstrap’s tooltip class includes few events for hooking into tooltip functionality.

    EventDescription
    show.bs.tooltipThis event fires immediately when the show instance method is called.
    shown.bs.tooltipThis event is fired when the tooltip has been made visible to the user. It will wait until the CSS transition process has been fully completed before getting fired.
    hide.bs.tooltipThis event is fired immediately when the hide instance method has been called.
    hidden.bs.tooltipThis event is fired when the tooltip has finished being hidden from the user. It will wait until the CSS transition process has been fully completed before getting fired.
    inserted.bs.tooltipThis event is fired after the show.bs.tooltip event when the tooltip template has been added to the DOM.

    The following example will display an alert message to the user when the fade out transition of the tooltip has been fully completed.

    Example

    jQuery JavaScript

    Try this code »

    <script>
    $(document).ready(function(){
        $("#myTooltip").on("hidden.bs.tooltip", function(){
            alert("Tooltip has been completely closed.");
        });
    });
    </script>
  • Bootstrap Collapse

    Toggle Display of Content with Bootstrap

    You can use the Bootstrap collapse JavaScript plugin to easily show and hide (or expand and collapse) specific elements on a web page. Buttons and anchors (i.e. the <button> and <a> elements) are typically used as triggers that are mapped to the elements you want to toggle.

    Expand and Collapse Elements via Data Attributes

    You can show and hide elements in Bootstrap by clicking on a button or link via data attributes without writing any JavaScript code. Let’s try out an example and see how it actually works:

    Example

    Try this code »

    <!-- Trigger Buttons HTML -->
    <a href="#myCollapse" data-bs-toggle="collapse">Toggle Element</a>
    <button type="button" class="btn btn-primary" data-bs-toggle="collapse" data-bs-target="#myCollapse">Toggle Element</button>
    
    <!-- Collapsible Element HTML -->
    <div class="collapse show" id="myCollapse">
        <div class="card card-body">This is a simple example of showing and hiding specific element via data attributes. Click any trigger buttons to toggle this panel.</div>
    </div>

    We’ve just created a collapsible control without writing any JavaScript code. Well, let’s go through each part of this code one by one for a better understanding.

    Explanation of Code

    The Bootstrap collapse plugin basically requires the two elements to work properly — the trigger element such as a button or hyperlink, and the collapsible element itself.

    • The data-bs-toggle="collapse" attribute is added to the trigger or controller element along with a attribute data-bs-target (for buttons) or href (for anchors) to automatically assign control of one or more collapsible elements.
    • The data-bs-target or href attribute accepts a CSS selector (such as id selector #myCollapse in our example) to apply the collapse to a specific element.
    • The class .collapse is added to the collapsible element (line no-6).
    • You can optionally add the class .show (line no-6) to the collapsible element in addition to the class .collapse to make it open by default.

    To make the collapsible controls to work in group like accordion menu, you can utilize the Bootstrap card component. See the tutorial on Bootstrap accordion to learn more about it.


    Expand and Collapse Elements via JavaScript

    You may also expand and collapse elements manually via JavaScript — just call the collapse() Bootstrap method with the id or class selector of the collapsible element.

    Example

    jQuery JavaScript

    Try this code »

    <script>
    $(document).ready(function(){
        $("#myBtn").click(function(){
            $("#myCollapse").collapse("toggle");
        });
    });
    </script>

    Options

    There are certain options which may be passed to the collapse() Bootstrap method to customize the functionality of a collapsible element.

    NameTypeDefault ValueDescription
    parentselectorfalseAll other collapsible elements under the specified parent will be closed while this collapsible item is shown on invocation.
    togglebooleantrueToggles the collapsible element on invocation.

    You can also set these options using the data attributes on accordion — just append the option name to data-bs-, like data-bs-parent="#myAccordion"data-bs-toggle="false".


    Methods

    These are the standard bootstrap’s collapse methods:

    Passing options

    You can additionally pass options to the collapse using options object.

    In following example the display of the collapsible element will not toggle on invocation, because the toggle option for the collapsible element is set to false.

    Example

    jQuery JavaScript

    Try this code »

    <script>
    $(document).ready(function(){
        $("#myBtn").click(function(){
            $("#myCollapse").collapse("toggle", {
                toggle: false
            });
        });
    });
    </script>

    toggle

    This method toggles (show or hide) a collapsible element.

    Example

    jQuery JavaScript

    Try this code »

    <script>
    $(document).ready(function(){
        $("#myBtn").click(function(){
            $("#myCollapse").collapse("toggle");
        });
    });
    </script>

    show

    This method shows a collapsible element.

    Example

    jQuery JavaScript

    Try this code »

    <script>
    $(document).ready(function(){
        $("#myBtn").click(function(){
            $("#myCollapse").collapse("show");
        });
    });
    </script>

    hide

    This method hides a collapsible element.

    Example

    jQuery JavaScript

    Try this code »

    <script>
    $(document).ready(function(){
        $("#myBtn").click(function(){
            $("#myCollapse").collapse("hide");
        });
    });
    </script>

    dispose

    This method destroys an element’s collapse (i.e. removes stored data on the DOM element).

    Example

    jQuery JavaScript

    Try this code »

    <script>
    $(document).ready(function() {
        $("#myBtn").click(function() {
            var myCollapse = bootstrap.Collapse.getInstance($("#myCollapse")[0]);
            console.log(myCollapse);
            // {_element: div#myCollapse.collapse.show, _isTransitioning: false, _config: {…}, _triggerArray: Array(2), _selector: "#myCollapse", …}
    
            $("#myCollapse").collapse("dispose");
            console.log(myCollapse);
            // {_element: null, _isTransitioning: null, _config: null, _triggerArray: null, _selector: null, …}
        });
    });
    </script>

    getInstance

    This is a static method which allows you to get the collapse instance associated with a DOM element.

    Example

    jQuery JavaScript

    Try this code »

    <script>
    $(document).ready(function(){
        $("#myBtn").click(function(){
            var myCollapse = bootstrap.Collapse.getInstance($("#myCollapse")[0]);
            console.log(myCollapse);
            // {_element: div#myCollapse.collapse.show, _isTransitioning: false, _config: {…}, _triggerArray: Array(2), _selector: "#myCollapse", …}
        });
    });
    </script>

    getOrCreateInstance

    This is a static method which allows you to get the collapse instance associated with a DOM element, or create a new one in case if the collapse wasn’t initialized.

    Example

    jQuery JavaScript

    Try this code »

    <script>
    $(document).ready(function(){
        $("#myBtn").click(function(){
            var myCollapse = bootstrap.Collapse.getOrCreateInstance($("#myCollapse")[0]);
            console.log(myCollapse);
        });
    });
    </script>

    Tip: Static methods cannot be called on instances of the class (i.e. objects). They’re called on the class itself. The keyword static is used to define a static method for a class.


    Events

    Bootstrap’s collapse class includes few events for hooking into collapse functionality.

    EventDescription
    show.bs.collapseThis event fires immediately when the show instance method is called.
    shown.bs.collapseThis event is fired when a collapse element has been made visible to the user. It will wait until the CSS transition process has been fully completed before getting fired.
    hide.bs.collapseThis event is fired immediately when the hide method has been called.
    hidden.bs.collapseThis event is fired when a collapse element has been hidden from the user. It will wait until the CSS transition process has been fully completed before getting fired.

    The following example displays an alert message to the user when sliding transition of a collapsible element has been fully completed.

    Example

    jQuery JavaScript

    Try this code »

    <script>
    $(document).ready(function(){
        $("#myCollapse").on("hidden.bs.collapse", function(){
            alert("Collapsible element has been completely closed.");
        });
    });
    </script>