How to Use Bootstrap JavaScript Components

The Bootstrap documentation, has a very large “Components” section that includes most of the stylized CSS Components that I explained before. However, there’s overlap between the Bootstrap CSS and JavaScript Components. CSS is used to style Components, while JavaScript is used to make Components functional.

Some Bootstrap Components only provide CSS-driven formatting and style so they don’t utilize JavaScript. These CSS-only Components were explored earlier in the Bootstrap CSS section: Badges, Breadcrumbs, Buttons, Cards, Form inputs, Jumbotron, Pagination.

But, most Components have JavaScript-driven behaviors:

You might also know that Bootstrap requires jQuery. This is because all of the Bootstrap JavaScript Components are implemented as jQuery Plugins. There are 2 ways to set options for (configure) any of the Bootstrap JavaScript Components.

Data Attributes

The preferred method is using Data Attributes. This method doesn’t require you to add additional JavaScript/jQuery code since the data- attribute can be used directly in the HTML markup. For example,

        <div id="myModal" class="modal" data-backdrop="false">
            <div class="modal-dialog">...</div>
        </div>

jQuery

The other way to use Bootstrap’s JavaScript Components is jQuery. Use the appropriate jQuery selector the element, and an Object containing the appropriate Options for the Component. The Options for each Component are described in the Bootstrap docs.

        $("#myModal").modal({backdrop:false})

As you can see the Component Options align with the data-attributes. Most Components are automatically initialized by simply using the appropriate Bootstrap data-toggle=”…” attribute and classes. Two exceptions are the Popover and Tooltip which must be manually initialized with jQuery. For example:

        $(function () {
          $('[data-toggle="popover"]').popover()
          $('[data-toggle="tooltip"]').tooltip()
        })

JavaScript Component Usage is clearly described in the Documentation which is the best reference and constantly maintained. Don’t rely on 3rd party tutorials and sites like W3Schools are they tend to get outdated quickly, and you’ll end-up wondering “Why is my Bootstrap not working?”.