Chapter 11: Using Bootstrap 5 with Advanced JavaScript Features

In this chapter, we will learn about some advanced JavaScript features that can be used with the interactive components of Bootstrap 5. First, we will get a quick overview of the interactive components and see which requirements they have in common in terms of dependencies and initialization. Then, we will see how we can initialize interactive components with either data attributes or JavaScript. Following this, we will see how we can define options with either data attributes or JavaScript, and finally, we will take a closer look at how we can use JavaScript for methods and events.

In this chapter, we’re going to cover the following main topics:

  • Interactive components of Bootstrap 5
  • Initializing interactive components
  • Defining options for interactive components
  • Using JavaScript methods
  • Using JavaScript events

Technical requirements

To preview the examples, you will need a code editor and a browser. The source code for all code examples can be found here:

https://github.com/PacktPublishing/The-Missing-Bootstrap-5-Guide

Interactive components of Bootstrap 5

We will start this chapter by getting an overview of the interactive components of Bootstrap 5. For each component listed here, we will see which JavaScript file is being used, whether it requires custom initialization, which options, methods, and events it has, whether it has any dependencies, and for some of them also some additional information. In the following sections, we will then look closer at initialization, options, methods, and events, so this should just be regarded as an overview. At the end of the list, there’s also a summary to highlight the most important differences.

Accordion

This component is built using the collapse component described later.

Alert

JavaScript file: alert.js

Custom initialization: No

Options: None

Methods: close, dispose, getInstance, getOrCreateInstance

Events: close.bs.alert, closed.bs.alert

Dependencies: None

This component can be dismissed with the close button component.

Button

JavaScript file: button.js

Custom initialization: No

Options: None

Methods: toggle, dispose, getInstance, getOrCreateInstance

Events: None

Dependencies: None

Carousel

JavaScript file: carousel.js

Custom initialization: No

Options: interval, keyboard, pause, ride, wrap, touch

Methods: cycle, pause, prev, next, nextWhenVisible, to, dispose, getInstance, getOrCreateInstance

Events: slide.bs.carousel, slid.bs.carousel

Dependencies: None

Collapse

JavaScript file: collapse.js

Custom initialization: No

Options: parent, toggle

Methods: toggle, show, hide, dispose, getInstance, getOrCreateInstance

Events: show.bs.collapse, shown.bs.collapse, hide.bs.collapse, hidden.bs.collapse

Dependencies: None

Dropdown

JavaScript file: dropdown.js

Custom initialization: No

Options: boundary, reference, display, offset, autoClose, popperConfig

Methods: toggle, show, hide, update, dispose, getInstance, getOrCreateInstance

Events: show.bs.dropdown, shown.bs.dropdown, hide.bs.dropdown, hidden.bs.dropdown

Dependencies: Popper

This component requires the external third-party library Popper for positioning. It must be included before bootstrap.js or by using bootstrap.bundle.js, which contains Popper.

List group

This component uses tab.js to create tab navigation based on list groups. Please refer to the details for navs and tabs, which use the same JavaScript file.

Modal

JavaScript file: modal.js

Custom initialization: No

Options: backdrop, keyboard, focus

Methods: toggle, show, hide, handleUpdate, dispose, getInstance, getOrCreateInstance

Events: show.bs.modal, shown.bs.modal, hide.bs.modal, hidden.bs.modal, hidePrevented.bs.modal

Dependencies: None

Navs and tabs

JavaScript file: tab.js

Custom initialization: No

Options: None

Methods: show, dispose, getInstance, getOrCreateInstance

Events: show.bs.tab, shown.bs.tab, hide.bs.tab, hidden.bs.tab

Dependencies: None

The JavaScript file used by this component is also used by the list group component.

Offcanvas

JavaScript file: offcanvas.js

Custom initialization: No

Options: backdrop, keyboard, scroll

Methods: toggle, show, hide, getInstance, getOrCreateInstance

Events: show.bs.offcanvas, shown.bs.offcanvas, hide.bs.offcanvas, hidden.bs.offcanvas

Dependencies: None

Popover

JavaScript file: popover.js

Custom initialization: Yes

Options: animation, container, content, delay, html, placement, selector, template, title, trigger, fallbackPlacements, boundary, customClass, sanitize, allowList, sanitizeFn, offset, popperConfig

Methods: show, hide, toggle, dispose, enable, disable, toggleEnabled, update, getInstance, getOrCreateInstance

Events: show.bs.popover, shown.bs.popover, hide.bs.popover, hidden.bs.popover, inserted.bs.popover

Dependencies: tooltip.js, Popover

This component requires tooltip.js as a dependency. It also requires the external third-party library Popper for positioning. The latter must be included before bootstrap.js or by using bootstrap.bundle.js, which contains Popper.

Scrollspy

JavaScript file: scrollspy.js

Custom initialization: No

Options: rootMargin, smoothScroll, target

Methods: refresh, dispose, getInstance, getOrCreateInstance

Events: activate.bs.scrollspy

Dependencies: None

Toast

JavaScript file: toast.js

Custom initialization: Yes

Options: animation, autohide, delay

Methods: show, hide, dispose, getInstance, getOrCreateInstance

Events: show.bs.toast, shown.bs.toast, hide.bs.toast, hidden.bs.toast

Dependencies: None

Tooltip

JavaScript file: tooltip.js

Custom initialization: Yes

Options: animation, container, delay, html, placement, selector, template, title, trigger, fallbackPlacements, boundary, customClass, sanitize, allowList, sanitizeFn, offset, popperConfig

Methods: show, hide, toggle, dispose, enable, disable, toggleEnabled, update, getInstance, getOrCreateInstance

Events: show.bs.tooltip, shown.bs.tooltip, hide.bs.tooltip, hidden.bs.tooltip, inserted.bs.tooltip

Dependencies: Popover

This component requires the external third-party library Popper for positioning. It must be included before bootstrap.js or by using bootstrap.bundle.js, which contains Popper.

The tooltip.js file is required by the popover component as a dependency.

We just ran through a list of all of the 15 components that use JavaScript in some way or another. Now, we will summarize this and highlight the most important differences among the components. Under the next four headings, we will therefore see which components stand out from the crowd.

Requires initialization

Components: Popover, toast, tooltip

These components can’t be initialized with the use of data attributes due to performance reasons. Hence, they must instead be initialized using custom JavaScript. We will see how in the Initializing interactive components section.

Has dependencies

Components: Dropdown, popover, tooltip

These components all require the external third-party library Popper for positioning. It must be included before bootstrap.js or by using bootstrap.bundle.js, which contains Popper.

In addition to this, the popover component also requires the tooltip.js JavaScript file from the tooltip component as a dependency.

Has no options

Components: Alert, button, navs, and tabs

These components don’t have any options.

Has no events

Component: Button

This component doesn’t have any events.

Initializing interactive components

In this section, we will see how we can initialize interactive components in two different ways. First, we will see how we can do it with data attributes in the HTML, which is the default way, which you might have already been using. Then, we will see how we can do it with JavaScript instead. We can initialize most of the interactive components that come with Bootstrap 5 using data attributes and without adding any extra JavaScript code ourselves, while some of them we must initialize with our own JavaScript.

Initializing interactive components using data attributes

We can initialize most of the interactive components that come with Bootstrap 5 using data attributes and without adding any extra JavaScript code ourselves. For most components, we use the data-bs-toggle data attribute, with the value being the name of the component, like so:

HTML

<button type="button" class="btn btn-primary" data-bs-toggle="button">Button</button>

However, for the carousel component, we must use data-bs-ride="carousel", for the scrollspy component we must use data-bs-spy="scroll", and, to dismiss the alert or offcanvas component, we must use data-bs-dismiss="[alert/offcanvas]".

Other required data attributes

Various other data attributes are required for some components to make them work. The data attributes mentioned above are just the ones used to initialize them.

Initializing interactive components using JavaScript

As we saw in the list at the beginning of this chapter, we must initialize some of the interactive components with our own JavaScript code.

As an example, we want to create a tooltip component for the following badge component:

HTML

<div class="badge bg-secondary" title="Tooltip for badge">Badge with tooltip</div>

The <div> tag has the title attribute that is used by the tooltip component.

Syntax

We can initialize an interactive component by using the constructor function in JavaScript to create and initialize an object instance of a class using the new keyword.

The syntax for this is as follows:

JavaScript

var tooltip = new bootstrap.Tooltip(element, options)

Here, element can be either a DOM element or a CSS selector and options is an object and is optional. Options can still be defined using data attributes, even though we are initializing a component with JavaScript. We will learn more about options in the Defining options for interactive components section.

Using a DOM element

To initialize an interactive component using a DOM element, we must first store it in a variable, and then use that variable as a reference to the DOM element. Here’s an example of how to do this:

part-3/chapter-11/examples/initialization/index.html line 14

<div class="badge bg-secondary" title="Tooltip for badge" id="tooltipDOM">Badge with tooltip</div>

part-3/chapter-11/examples/initialization/js/script.js line 1-2

var tooltipDOMelement = document.getElementById('tooltipDOM');
var tooltipDOM = new bootstrap.Tooltip(tooltipDOMelement);

In the previous code, we stored the element with id="tooltipDOM" in the element variable, which we then passed as an argument to the constructor function. We didn’t pass any options since we will take a closer look at that later in this chapter.

Using a CSS selector

To initialize an interactive component using a CSS selector, we can simply pass it as the argument to the constructor function. The element is then found using the querySelector() method. Here’s an example of how to do this using the ID of the <div> element as the selector:

part-3/chapter-11/examples/initialization/index.html line 19

<div class="badge bg-secondary" title="Tooltip for badge" id="tooltipCSS">Badge with tooltip</div>

part-3/chapter-11/examples/initialization/js/script.js line 4

var tooltip = new bootstrap.Tooltip('#tooltipCSS');

Initializing multiple components

The various JavaScript plugins for the interactive components only support a single element. So, to initialize multiple elements, we can call the constructor function for each element in a list or an array. We will now see two different examples of how we can do just that.

Using a for loop

For the first example, we will use the following HTML with three identical badge components that all have the same tooltipLoop class:

part-3/chapter-11/examples/initialization/index.html line 24-26

<div class="badge bg-secondary tooltipLoop" title="Tooltip for badge">Badge with tooltip</div>
<div class="badge bg-secondary tooltipLoop" title="Tooltip for badge">Badge with tooltip</div>
<div class="badge bg-secondary tooltipLoop" title="Tooltip for badge">Badge with tooltip</div>

When using a for loop, we first store all <div> elements in the tooltipLoopElements variable. Then, we loop through this NodeList and call the constructor function for each element:

part-3/chapter-11/examples/initialization/js/script.js line 6-9

var tooltipLoopElements = document.querySelectorAll('.tooltipLoop');
for (var i = 0; i < tooltipLoopElements.length; i++) {
  new bootstrap.Tooltip(tooltipLoopElements[i])
}

Using the map method

For the second example, we will use the following HTML with three identical badge components that all have the same tooltipMap class:

part-3/chapter-11/examples/initialization/index.html line 31-33

<div class="badge bg-secondary tooltipMap" title="Tooltip for badge">Badge with tooltip</div>
<div class="badge bg-secondary tooltipMap" title="Tooltip for badge">Badge with tooltip</div>
<div class="badge bg-secondary tooltipMap" title="Tooltip for badge">Badge with tooltip</div>

When using the map() method, we first store all <div> elements in the tooltipMapElements variable. However, this time we use the slice() and call() methods to turn the NodeList into an array. Then, we create a new array using the map() method and store it in the tooltipMap variable. For every element in the array, we call the constructor function like before:

part-3/chapter-11/examples/initialization/js/script.js line 11-14

var tooltipMapElements = [].slice.call(document.querySelectorAll('.tooltipMap'));
var tooltipMap = tooltipMapElements.map(function(tooltipMapElement) {
  return new bootstrap.Tooltip(tooltipMapElement)
});

Data attribute required for the dropdown component

Even if you choose to initialize the dropdown component using JavaScript, the data-bs-toggle="dropdown" data attribute is still required on the trigger element for the dropdown.

We have now learned how to initialize interactive components in various ways. We will continue to learn how to define options for interactive components.

Defining options for interactive components

In the list at the beginning of this chapter, we saw which options were available for interactive components. In the official documentation of Bootstrap 5, you will find a table describing all of the available options (if any) for each component. In this table, you will find the name, type, default value, and description for each option. You can access the components in the official documentation through this link: getbootstrap.com/docs/5.1/components.

Default options for all components of a type and common options for a group of components can be set via JavaScript, while options for individual components can be passed either via data attributes or via JavaScript. Let’s now see how this is done.

Defining default options

You can change the default value for an option for a component by using the following syntax:

JavaScript

bootstrap.[component name].Default.[option name] = [option value];

As an example, we can set our tooltip components to have a default delay of 1,000 milliseconds in the following way:

JavaScript

bootstrap.Tooltip.Default.delay = 1000;

Defining options using data attributes

To define options using data attributes, we append the option name to data-bs-, and the case type of the option name should be changed from camelCase to kebab-case.

Now, let’s see how we can initialize a tooltip component with an option for how to trigger it. For this purpose, we can use the trigger option, which accepts a value of the string type. The default is ‘hover focus’, and the possible values are ‘click | hover | focus | manual’. We will make the tooltip trigger on click only using the following code:

HTML

<a href="#" id="tooltip" title="Tooltip for link" data-bs-trigger="click">Link</a>

The tooltip will now only be triggered on click for both showing and hiding – just like the popover component. Keep in mind that the previous code on its own will not initialize the tooltip component. As we just learned, this must be done with our own JavaScript code:

Options that can’t be set using data attributes

The following options used by the popover and tooltip components can’t be set using data attributes due to security reasons: sanitizesanitizeFn, and allowList. These are all related to using HTML in the content of the tooltip or popover.

Defining options using JavaScript

As mentioned earlier in this chapter, it’s possible to pass an optional options object to the constructor when initializing an interactive component with JavaScript. To repeat, the syntax looks like this:

var tooltip = new bootstrap.Tooltip(element, options)

To define an option with an object, we simply use the option name as a property of the object and then give it a valid value depending on the type of option. Initializing the same tooltip component as before, with the trigger option set to click, will then look like this:

HTML

<a href="#" id="tooltip" title="Tooltip for link">Link</a>

JavaScript

var tooltip = new bootstrap.Tooltip('#tooltip', { trigger: 'click' })

The tooltip will now only be triggered on click for both showing and hiding.

Defining default, common, and individual options

As mentioned previously, we can define default, common, and individual options for components using JavaScript and data attributes. This is useful if you want to define some default options for all components of a type, options with the same value for a group of components, and individual options with different values for each instance of a component.

We will now see an example where we make use of all of this. In our HTML, we have four badge components to which we want to add a tooltip component. On each of the <div> elements, we define the placement for the tooltip using the data-bs-placement data attribute:

part-3/chapter-11/examples/options/index.html

<div class="badge bg-secondary tooltipOnClick" title="Tooltip on top" data-bs-placement="top">Badge with tooltip on top</div>
<div class="badge bg-secondary tooltipOnClick" title="Tooltip on bottom" data-bs-placement="bottom">Badge with tooltip on bottom</div>
<div class="badge bg-secondary tooltipOnClick" title="Tooltip on left" data-bs-placement="left">Badge with tooltip on left</div>
<div class="badge bg-secondary tooltipOnClick" title="Tooltip on right" data-bs-placement="right">Badge with tooltip on right</div>

Then, in our JavaScript, we first define the default option for delay and set it to 1000 milliseconds. After that, we initialize the components using JavaScript with the trigger option set to ‘click’:

part-3/chapter-11/examples/options/js/script.js

bootstrap.Tooltip.Default.delay = 1000;
var tooltipElementList = document.querySelectorAll('.tooltipOnClick');
for (var i = 0; i < tooltipElementList.length; i++) {
    new bootstrap.Tooltip(tooltipElementList[i], { trigger: 
      'click' })
}

The four badge components will now have a tooltip component each that will trigger on click with a delay of 1,000 milliseconds. The tooltips will be placed at the top, bottom, left, and right respectively.

Using data attributes and JavaScript for the same option

If you specify the same option with both a data attribute and using JavaScript, the JavaScript setting will take precedence.

Using JavaScript methods

In the list at the beginning of this chapter, we saw that all interactive components have methods. In the official documentation of Bootstrap 5, you will find a table describing all of the available methods for each component. In this table, you will find the name and description for each method. You can access the components in the official documentation through this link: getbootstrap.com/docs/5.2/components.

Now, we will see some examples of how to use specific methods for the tooltip component. In our example page, we first have a default tooltip component for comparison. The HTML for this is as follows:

part-3/chapter-11/examples/methods/index.html line 15

<div class="badge bg-secondary" id="tooltipDefault" title="Default tooltip">Badge with default tooltip</div>

The tooltip has the id="tooltipDefault" attribute, which we use to initialize it with the following JavaScript:

part-3/chapter-11/examples/methods/js/script.js line 1

var tooltipDefault = new bootstrap.Tooltip('#tooltipDefault', { placement: "bottom" });

As we can see, the tooltip is placed at the bottom using the placement option. This is simply to make the example page better visually.

For the next tooltip component on the example page, we want it to show when the page loads and, at the same time, disable triggering on hover and focus. The HTML is as follows:

part-3/chapter-11/examples/methods/index.html line 21

<div class="badge bg-secondary" id="tooltipOnLoad" title="Tooltip triggered on load">Badge with tooltip triggered on load</div>

The tooltip has the id="tooltipOnLoad" attribute, which we will use for initialization. The JavaScript code looks like this:

part-3/chapter-11/examples/methods/js/script.js line 3-4

var tooltipOnLoad = new bootstrap.Tooltip('#tooltipOnLoad', { trigger: "manual", placement: "bottom" });
tooltipOnLoad.show();

The tooltip is placed at the bottom using the placement option and the method to trigger the tooltip is set to manual. This means that the tooltip will be triggered programmatically using JavaScript, which is exactly what we do in the line below where we call the show() method on the initialized tooltip component.

For our final tooltip component on the example page, we want to toggle its visibility when we click a button placed elsewhere on the page. The HTML for this is as follows:

part-3/chapter-11/examples/methods/index.html line 27-28

<button type="button" id="triggerForTooltip" class="btn btn-secondary mb-4">Trigger for tooltip</button><br>
<div class="badge bg-secondary" id="tooltipOnButtonClick" title="Tooltip toggled on button click">Badge with tooltip toggled on button click</div>

The button has the id="triggerForTooltip" attribute, which we will use to attach an event listener, and the tooltip has the id="tooltipOnButtonClick" attribute, which we will use for initialization. The JavaScript code looks like this:

part-3/chapter-11/examples/methods/js/script.js line 6-10

var tooltipOnButtonClick = new bootstrap.Tooltip('#tooltipOnButtonClick', { trigger: "manual", placement: "bottom" });
var triggerForTooltip = document.getElementById('triggerForTooltip');
triggerForTooltip.addEventListener('click', function() {
  tooltipOnButtonClick.toggle();
})

The first line is similar to the previous example: the tooltip is placed at the bottom using the placement option and the method to trigger the tooltip is set to manual. Below that, we first get the button element and then attach a click event to it and execute the toggle() method when the button is clicked. This will show and hide the tooltip.

Asynchronous methods and transitions

It’s important to know that all methods are asynchronous and start a transition. As soon as that transition is started, they return to the caller. This means that a method call on a component that is currently transitioning is ignored. Take the following example, which will show the modal, but not hide it, since the hide() method is called immediately after show() and therefore before the transition to show that the modal is finished:

JavaScript

var modalElement = document.getElementById('modal');
var modal = bootstrap.Modal.getOrCreateInstance(modalElement);
modal.show();
modal.hide();

Instead, if we want to execute some code when the transition is finished, we need to listen to the corresponding event, like so:

JavaScript

var modalElement = document.getElementById('modal');
var modal = bootstrap.Modal.getOrCreateInstance(modalElement);
modal.show();
modalElement.addEventListener('shown.bs.modal', function (event) {
  modal.hide();
})

Now, the modal will first show and then hide again when the modal’s shown event is fired. In the next section, we will see another example of how to use Bootstrap 5 events.

Using JavaScript events

In the list at the beginning of this chapter, we saw that most interactive components have events. In the official documentation of Bootstrap 5, you will find a table describing all of the available events for each component. In this table, you will find the event type and description for each method. You can access the components in the official documentation through this link: getbootstrap.com/docs/5.2/components.

Now, we will see an example of how to use a specific event for the tooltip component. In our example page, we have a button that triggers a modal component. In the modal footer, we have a Confirm button on which we want to show a tooltip when the modal is shown and the transition is finished.

Here’s what the HTML looks like:

part-3/chapter-11/examples/events/index.html

<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#modal">Open modal</button>
<div class="modal fade" id="modal" tabindex="-1" aria-labelledby="modalTitle" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="modalTitle">Modal 
          title</h5>
        <button type="button" class="btn-close" data-bs-
          dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <p>Lorem ipsum dolor sit amet, consectetur 
           adipiscing elit. In laoreet pellentesque lorem 
           sed elementum. Suspendisse maximus convallis ex. 
           Etiam eleifend velit leo.</p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-primary" 
          id="tooltip" title="Click here to 
          confirm">Confirm</button>
        <button type="button" class="btn btn-secondary" 
          data-bs-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>

The tooltip has the id="tooltip", which we will use for initialization, and the content for the tooltip is placed in a title attribute. In the JavaScript code, we first store the DOM element of the modal in a variable and initialize the tooltip component. Then, in an event listener attached to the modal, we listen to the shown.bs.modal event and call the show() method on the tooltip component when it fires. The JavaScript code for this is as follows:

part-3/chapter-11/examples/events/js/script.js

var modal = document.getElementById('modal');
var tooltip = new bootstrap.Tooltip('#tooltip');
modal.addEventListener('shown.bs.modal', function (event) {
  tooltip.show();
})

This example will now show the tooltip exactly when the transition for the modal is finished.

Events with properties

The two events for the carousel component have the following additional properties: direction ("left" or "right"), relatedTarget (DOM element), from (index number), and to (index number).

Summary

In this chapter, we have learned about some advanced JavaScript features that can be used with the interactive components of Bootstrap 5. First, we got a quick overview of the interactive components and saw which requirements they have in common in terms of dependencies and initialization. Then, we saw how we can initialize interactive components with either data attributes or JavaScript. Following this, we saw how we can define options with either data attributes or JavaScript, and finally, we took a closer look at how we can use JavaScript for methods and events.

In the next and final chapter of this book, we will learn how to optimize the compiled Bootstrap 5 CSS and JavaScript code.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset