Bootstrap - Interactions

-

Bootstrap Interactions

Interactions play a role in web design, as they engage users and improve the user experience. Bootstrap, a CSS framework, offers interactive components that you can use to create dynamic websites. These interactions allow users to interact with the website, providing an immersive experience.

Interactions are important for:

  1. User engagement
  2. Usability
  3. Visual feedback
  4. Better user experience

Collapse

The collapse component in Bootstrap lets you hide and show content on your web page. It lets users toggle the visibility of sections, which can be useful for creating accordions, expandable panels, or revealing more information on demand.

To create a collapsible element, wrap the content you want to collapse within a container element, such as a <div>. Add the .collapse class to the content element to indicate that it should be hidden by default. Then, create a trigger element, like a button or a link, and add the data-bs-toggle="collapse" attribute to it, along with the data-bs-target="#elementID" or href="#elementID" attribute to specify the ID of the collapsible content.

Example

<button class="btn btn-primary" type="button" data-bs-toggle="collapse" data-bs-target="#collapseExample">
  Toggle Collapse
</button>

<div class="collapse" id="collapseExample">
  <div class="card card-body">
    This content is collapsible. It can be hidden or shown by clicking the button above.
  </div>
</div>

Bootstrap's collapse component can be used to create an accordion, which is a group of collapsible elements where only one element can be expanded at a time. To create an accordion, wrap the collapsible elements within a parent container, such as a <div>, and give each collapsible element a unique ID. Use the data-bs-parent="#parentID" attribute on the trigger elements to specify the ID of the parent container, ensuring that only one collapsible element is open at a time.

Example

<div class="accordion" id="accordionExample">
  <div class="accordion-item">
    <h2 class="accordion-header" id="headingOne">
      <button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#collapseOne" data-bs-parent="#accordionExample">
        Accordion Item #1
      </button>
    </h2>
    <div id="collapseOne" class="accordion-collapse collapse show">
      <div class="accordion-body">
        This is the first item's accordion body.
      </div>
    </div>
  </div>
  <div class="accordion-item">
    <h2 class="accordion-header" id="headingTwo">
      <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseTwo" data-bs-parent="#accordionExample">
        Accordion Item #2
      </button>
    </h2>
    <div id="collapseTwo" class="accordion-collapse collapse">
      <div class="accordion-body">
        This is the second item's accordion body.
      </div>
    </div>
  </div>
</div>

The behavior of the collapse component can be controlled using data attributes. You can use data-bs-toggle="collapse" on the trigger element to toggle the visibility of the collapsible content when clicked. The data-bs-target="#elementID" or href="#elementID" attribute specifies the ID of the target collapsible element. To have a collapsible element open by default, add the .show class to the content element.

Bootstrap's collapse component also provides JavaScript methods and events for programmatic control. You can use the collapse() method to manually show or hide a collapsible element. The show.bs.collapse and shown.bs.collapse events are fired when the collapsible element starts and finishes expanding, respectively. Similarly, the hide.bs.collapse and hidden.bs.collapse events are triggered when the collapsible element starts and finishes collapsing.

The collapse component in Bootstrap is a powerful tool for creating interactive and expandable sections on your web page. It allows users to selectively view content, making your web page more organized and user-friendly.

Modals

Modals are dialog boxes or popup windows that appear on top of the main content, providing a way to display more information, ask for user input, or show notifications. Bootstrap offers a built-in modal component that lets you create dynamic modals with ease.

To create a basic modal in Bootstrap, you need a trigger element, such as a button, and a modal container. The modal container should have the .modal class and a unique ID. Inside the modal container, add a .modal-dialog element to wrap the modal content. The modal content consists of three main parts: the header (.modal-header), the body (.modal-body), and the footer (.modal-footer).

Example: Basic Modal

<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal">
  Launch demo modal
</button>

<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        Modal content goes here.
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>

Bootstrap provides different modal sizes and variations. You can create larger or smaller modals by adding the .modal-lg or .modal-sm class to the .modal-dialog element, respectively. To create a full-screen modal, use the .modal-fullscreen class on the .modal-dialog.

To center the modal vertically on the page, add the .modal-dialog-centered class to the .modal-dialog element. This makes the modal appear in the middle of the viewport, providing a more visually appealing presentation.

Modals can be toggled via JavaScript using the modal plugin. To show a modal, use the modal() method on the modal element. To hide a modal, use the modal('hide') method.

The modal plugin provides various options and methods for customizing and controlling modals. Some commonly used options include backdrop (boolean or 'static') to specify whether to include a backdrop element or make it static, keyboard (boolean) to control whether the modal should be closed when the escape key is pressed, and focus (boolean) to control whether the modal should automatically focus on the first focusable element within the modal.

Modal events such as show.bs.modal, shown.bs.modal, hide.bs.modal, and hidden.bs.modal are fired at different stages of the modal's lifecycle. You can listen to these events to perform actions or update the modal's content dynamically.

Tip: Triggering Actions with Modal Events

Use modal events to trigger specific actions or update the modal's content dynamically. For example, you can use the shown.bs.modal event to initialize form fields or load data via AJAX when the modal is displayed.

Bootstrap modals provide a way to present more content or prompt users for input without navigating away from the current page. By using the modal component and its options and methods, you can create engaging and interactive modals that improve the user experience on your website.

Tooltips

Tooltips are small pop-up boxes that appear when a user hovers over, focuses on, or clicks an element. They provide extra information about the element without cluttering the page. Tooltips are helpful for giving context, explaining functionality, or showing additional details about an item.

To enable tooltips in Bootstrap, add the data-bs-toggle="tooltip" attribute to an element, such as a button or a link. Then, specify the tooltip text using the title attribute.

Example: Enabling tooltips

<button type="button" class="btn btn-secondary" data-bs-toggle="tooltip" title="Tooltip text">
  Hover over me
</button>

Bootstrap provides options for positioning tooltips relative to the target element. Use the data-bs-placement attribute to set the tooltip's position. The available options are top, right, bottom, and left. By default, tooltips are positioned on top of the element.

Example: Tooltip positioning

<button type="button" class="btn btn-secondary" data-bs-toggle="tooltip" data-bs-placement="right" title="Tooltip on right">
  Tooltip on right
</button>

Tooltips can be triggered on hover or click. By default, tooltips are triggered when hovering over the element. To change the trigger to click, use the data-bs-trigger="click" attribute on the element.

Example: Tooltip trigger

<button type="button" class="btn btn-secondary" data-bs-toggle="tooltip" data-bs-trigger="click" title="Click-triggered tooltip">
  Click me
</button>

You can customize the appearance of tooltips by modifying the tooltip CSS classes. Bootstrap provides the .tooltip class for styling the tooltip container and the .tooltip-inner class for styling the tooltip content. Use CSS to change the background color, text color, font size, padding, and other visual properties of the tooltip.

Example: Customizing tooltip appearance

.tooltip-inner {
  background-color: #ff0000;
  color: #ffffff;
  font-size: 14px;
  padding: 8px;
}

The Bootstrap tooltip plugin provides methods and events for programmatically controlling tooltips. Use the show and hide methods to display or hide a tooltip, respectively. The dispose method removes the tooltip from the element.

Tooltip events, such as show.bs.tooltip, shown.bs.tooltip, hide.bs.tooltip, and hidden.bs.tooltip, are fired at different stages of the tooltip's lifecycle. You can listen to these events to perform actions or update the tooltip's content dynamically.

Example: Programmatic control and events

var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'))
var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
  return new bootstrap.Tooltip(tooltipTriggerEl)
})

// Show a tooltip
tooltipList[0].show()

// Hide a tooltip
tooltipList[0].hide()

// Listen to tooltip events
var myTooltip = document.getElementById('myTooltip')
myTooltip.addEventListener('shown.bs.tooltip', function () {
  console.log('Tooltip is shown')
})

Popovers

Popovers in Bootstrap are similar to tooltips but provide more content and customization options. They display additional information or functionality when a user interacts with an element. Popovers can contain text, images, or form elements.

To create a basic popover, add the data-bs-toggle="popover" attribute to an element, such as a button or a link. Specify the popover's title using the title attribute and its content using the data-bs-content attribute.

Example: Basic Popover

<button type="button" class="btn btn-secondary" data-bs-toggle="popover" title="Popover title" data-bs-content="Popover content goes here.">
  Click to toggle popover
</button>

Bootstrap provides options for placing popovers around the target element. Use the data-bs-placement attribute to set the popover's position. The available options are top, right, bottom, and left. By default, popovers are positioned on the right side of the element.

Example: Popover Placement

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

Popovers can be triggered on hover, click, or focus. By default, popovers are triggered on click. To change the trigger, use the data-bs-trigger attribute with the values hover, click, or focus.

Example: Popover Trigger

<button type="button" class="btn btn-secondary" data-bs-toggle="popover" data-bs-trigger="hover" title="Popover title" data-bs-content="Popover content goes here.">
  Hover to show popover
</button>

You can customize the content and appearance of popovers by using HTML and CSS. The popover's content can include text, images, links, or any valid HTML. Use the .popover class to style the popover container and the .popover-header and .popover-body classes to style the popover's title and content.

Example: Custom Popover

<button type="button" class="btn btn-secondary" data-bs-toggle="popover" title="Custom Popover" data-bs-html="true" data-bs-content="<div><img src='image.jpg' alt='Popover Image'><p>Custom popover content with <a href='#'>links</a> and images.</p></div>">
  Custom popover
</button>
.popover {
  max-width: 300px;
}
.popover-header {
  background-color: #f7f7f7;
  font-weight: bold;
}
.popover-body {
  padding: 10px;
}

The Bootstrap popover plugin provides methods and events for programmatically controlling popovers. Use the show, hide, and toggle methods to display, hide, or toggle a popover. The dispose method removes the popover from the element.

Popover events, such as show.bs.popover, shown.bs.popover, hide.bs.popover, and hidden.bs.popover, are fired at different stages of the popover's lifecycle. You can listen to these events to perform actions or update the popover's content dynamically.

Example: Popover Methods and Events

var popoverTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="popover"]'))
var popoverList = popoverTriggerList.map(function (popoverTriggerEl) {
  return new bootstrap.Popover(popoverTriggerEl)
})

// Show a popover
popoverList[0].show()

// Hide a popover
popoverList[0].hide()

// Listen to popover events
var myPopover = document.getElementById('myPopover')
myPopover.addEventListener('shown.bs.popover', function () {
  console.log('Popover is shown')
})

Toasts

Bootstrap toasts are notifications that copy the push notifications found in mobile and desktop operating systems. They show short, auto-expiring messages to users without stopping their interaction with the website.

To make a simple toast notification, create a container element with the .toast class. Inside the container, add a .toast-header element to show the title and optional close button, and a .toast-body element to hold the main content of the toast.

Example: Simple Toast Notification

<div class="toast" role="alert" aria-live="assertive" aria-atomic="true">
  <div class="toast-header">
    <strong class="me-auto">Bootstrap</strong>
    <small>11 mins ago</small>
    <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
  </div>
  <div class="toast-body">
    Hello, world! This is a toast message.
  </div>
</div>

You can change the look and behavior of toasts by adding classes and attributes. Use the .bg-* classes to change the background color of the toast, such as .bg-primary, .bg-success, or .bg-danger. Add the .text-* classes to change the text color, like .text-white or .text-muted.

To control how long the toast stays visible, use the data-bs-delay attribute on the .toast element. Set the duration in milliseconds, after which the toast will automatically hide.

Example: Toast with Custom Color and Delay

<div class="toast bg-success text-white" role="alert" aria-live="assertive" aria-atomic="true" data-bs-delay="3000">
  <div class="toast-header">
    <strong class="me-auto">Success</strong>
    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="toast" aria-label="Close"></button>
  </div>
  <div class="toast-body">
    Your action was successful!
  </div>
</div>

Bootstrap lets you stack toasts together and position them on the page. To stack toasts, wrap them inside a container element with the .toast-container class. Use the .position-absolute and .top-0, .end-0, .bottom-0, or .start-0 classes to position the container in the corners of the viewport.

Example: Stacked Toasts

<div class="position-fixed bottom-0 end-0 p-3" style="z-index: 11">
  <div class="toast-container">
    <div class="toast" role="alert" aria-live="assertive" aria-atomic="true">
      <!-- Toast content -->
    </div>
    <div class="toast" role="alert" aria-live="assertive" aria-atomic="true">
      <!-- Toast content -->
    </div>
  </div>
</div>

To show or hide toasts with JavaScript, use the show() and hide() methods provided by the toast plugin. You can trigger these methods on a specific toast element to control its visibility.

Example: Controlling Toasts with JavaScript

var toastElList = [].slice.call(document.querySelectorAll('.toast'))
var toastList = toastElList.map(function (toastEl) {
  return new bootstrap.Toast(toastEl)
})

// Show a toast
toastList[0].show()

// Hide a toast
toastList[0].hide()

The toast plugin offers options and methods to customize the behavior of toasts. Some commonly used options include animation (boolean) to control whether the toast should fade in and out, autohide (boolean) to specify if the toast should automatically hide after a certain duration, and delay (number) to set the delay in milliseconds before the toast is hidden.

Event Description
show.bs.toast Perform actions when a toast is shown
shown.bs.toast Perform actions after a toast is fully shown
hide.bs.toast Perform actions when a toast is hidden
hidden.bs.toast Perform actions after a toast is fully hidden

Bootstrap toasts provide a simple way to show short, informative messages to users. By customizing their look, stacking them together, and controlling their visibility through JavaScript, you can create engaging notifications that improve the user experience on your website.

Scrollspy

Scrollspy is a feature in Bootstrap that updates navigation links based on the user's scrolling position on the page. It highlights the active section in the navigation, making it easy for users to keep track of their location within long content. Scrollspy is useful for creating sidebars, table of contents, or navigation menus that scroll with the content.

To set up scrollspy in Bootstrap, add the data-bs-spy="scroll" attribute to the element that contains the scrollable content, such as the <body> tag. Then, specify the target navigation element using the data-bs-target attribute, pointing to the ID or class of the navigation container.

Example

<body data-bs-spy="scroll" data-bs-target="#navbar-example">
  ...
  <nav id="navbar-example">
    <ul class="nav nav-pills">
      <li class="nav-item">
        <a class="nav-link" href="#section1">Section 1</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#section2">Section 2</a>
      </li>
      ...
    </ul>
  </nav>
  ...
</body>

Example

<nav id="navbar-example2" class="navbar navbar-light bg-light px-3">
  <a class="navbar-brand" href="#">Navbar</a>
  <ul class="nav nav-pills">
    <li class="nav-item">
      <a class="nav-link" href="#section1">Section 1</a>
    </li>
    <li class="nav-item">
      <a class="nav-link" href="#section2">Section 2</a>
    </li>
    <li class="nav-item">
      <a class="nav-link" href="#section3">Section 3</a>
    </li>
  </ul>
</nav>

<div data-bs-spy="scroll" data-bs-target="#navbar-example2" data-bs-offset="0" class="scrollspy-example" tabindex="0">
  <h4 id="section1">Section 1</h4>
  <p>...</p>
  <h4 id="section2">Section 2</h4>
  <p>...</p>
  <h4 id="section3">Section 3</h4>
  <p>...</p>
</div>

You can customize the behavior of scrollspy by using data attributes or JavaScript options. Some commonly used options include offset (number) to specify the number of pixels to offset from the top when calculating the scroll position, and method (string) to set the method used to update the active link, either "auto" or "manual".

Tip

Use the data-bs-offset attribute to adjust the offset pixels for the scrollspy. This is useful when you have a fixed navigation bar that covers part of the content.

The scrollspy plugin provides methods and events for controlling and responding to scrollspy behavior. Use the refresh method to refresh the scrollspy and recalculate the positions of the target elements. The activate.bs.scrollspy event is fired whenever a new item becomes activated by the scrollspy.

Example

var scrollspy = new bootstrap.ScrollSpy(document.body, {
  target: '#navbar-example'
})

// Refresh the scrollspy
scrollspy.refresh()

// Listen to scrollspy activate event
document.body.addEventListener('activate.bs.scrollspy', function (event) {
  console.log('Scrollspy activated:', event.relatedTarget)
})