Skip to content

Instantly share code, notes, and snippets.

@kingluddite
Created May 11, 2024 11:30
Show Gist options
  • Save kingluddite/b66704b9f1f416a57e69d4e39886aba1 to your computer and use it in GitHub Desktop.
Save kingluddite/b66704b9f1f416a57e69d4e39886aba1 to your computer and use it in GitHub Desktop.
How does BS5 use data-attributes?

Bootstrap 5, like its predecessors, uses data attributes extensively to enhance the functionality and behavior of its components. Data attributes in Bootstrap serve as hooks for JavaScript plugins and provide configuration options for various components. Here are some common ways Bootstrap 5 utilizes data attributes:

  1. Data Toggle Attributes: Bootstrap components often use data attributes to toggle the visibility or behavior of certain elements. For example, the data-bs-toggle attribute is commonly used to toggle the visibility of dropdowns, modals, tooltips, and collapsible elements.

    <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal">
      Launch demo modal
    </button>
  2. Data Target Attributes: Components that interact with other elements, such as modals, tooltips, and popovers, often use the data-bs-target attribute to specify the target element that should be affected.

    <button type="button" class="btn btn-primary" data-bs-toggle="popover" data-bs-target="#examplePopover">
      Popover Example
    </button>
  3. Data Options Attributes: Some Bootstrap components allow you to specify additional options via data attributes. These attributes provide a convenient way to configure component behavior without writing JavaScript code.

    <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true" data-bs-backdrop="static" data-bs-keyboard="false">
      <!-- Modal content -->
    </div>
  4. Data API Initialization: Bootstrap's JavaScript plugins automatically initialize components based on data attributes present in the HTML markup. This allows developers to include components without writing any JavaScript code manually.

    <!-- Automatically initialize all tooltips on the page -->
    <script>
      var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'))
      var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
        return new bootstrap.Tooltip(tooltipTriggerEl)
      })
    </script>

Overall, data attributes in Bootstrap 5 provide a declarative way to configure and interact with components, making it easier to develop responsive and interactive web applications without writing extensive JavaScript code.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment