Read First

Alright, welcome to the demo page! Please make sure to check the Wiki pages, as they give you a quick start with everything else that isn't covered in this page, things like installing or using the library and other valuable guides on how to get the best out of it. Be sure to also check the pulse on the development or report any issues.

Alert

The Alert component covers the specific original events and public methods, but just like the original plugin, does not provide any initialization option. It covers most essential JavaScript and DATA API, and does not require the class alert-dismissible for the initialization to work, however the show class must be present in order for its main method to work.

Alert Methods

The Alert component exposes two public methods and a static method to be used via JavaScript:

instance.close()

The method hides an initialized alert and removes the <div class="alert"> element from the DOM.

instance.dispose()

Removes the component from target element. If the alert has been closed, calling this method should produce no effect, since the alert was already removed from the DOM.

Alert.getInstance()

A static method that allows you to access an Alert instance associated to a DOM element.

Alert Events

The component's original events are same as with the original component. The event.target of the events is the <div class="alert"> element, and not the button with the data-bs-dismiss="alert" attribute.

Event Type Description
close.bs.alert This event is fired immediately when the close instance method has been called.
This event can be default prevented.
closed.bs.alert This event is fired when the alert has finished being hidden from the user.

Alert DATA API

The component will initialize all elements with proper DATA API found in the DOM. Note that the data-bs-dismiss="alert" attribute is required for the triggering button. Also note that, differently from the original version, the show class is required for its main method.

<!-- notice the <button> with the data-bs-dismiss="alert" attribute -->
<div class="alert alert-warning alert-dismissible fade show" role="alert">
  <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
  Some critical notice.
</div>

In this example the Alert component will find a child element of the <div class="alert"> with the data-bs-dismsiss="alert" attribute to use it as a trigger for its .close() public method.

Alert JavaScript API

After inserting a new alert into the page, you can initialize it via JavaScript. Considering the above markup, you can do the following:

// initialize
var myWarningAlertInit = new BSN.Alert('.alert');

Also attach listeners to the original events:

// close.bs.alert
myAlert.addEventListener('close.bs.alert', function(event){
  // this event can be default prevented 
  // do something cool
  // event.target is <div class="alert">
}, false);

// closed.bs.alert
myAlert.addEventListener('closed.bs.alert', function(event){
  // do something cool
  // event.target is <div class="alert">
}, false);

Similar to the original library, all components of this library expose a static method that allows you to easily access the instance even if it was created via the DATA API:

// find an element initialized via DATA API
var myAlert = document.querySelector('.alert');

// get the initialization object
var myAlertInit = BSN.Alert.getInstance(myAlert);

// apply the public methods
myAlertInit.close();
// or 
myAlertInit.dispose();

Alert Examples

This alert has some listeners attached to close.bs.alert and closed.bs.alert events, so check your console.

This alert uses the closed.bs.alert event to show another alert.

Button

The Button component provides state toggle functionality identical to the original plugin. Our previously featured component has been completely deprecated, just like the original plugin. The functionality of the previous component has been replaced by a new HTML markup and CSS style that requires no scripting.

The component state toggle functionality is very simple: when the user clicks the button, the component adds / removes the active class name as well as change its aria-pressed attribute to true / false, both actions signalling the state and appearence of that particular button. However if the button is disabled, the state toggling is prevented.

Button Methods

instance.toggle()

Toggles the state of a button. When pushed it changes the appearence of the button.

instance.dispose()

Removes the component from target element. Its toggle state is not changed.

Button.getInstance()

A static method that allows you to access a Button instance associated to a DOM element.

Button DATA API

The component will initialize all elements with the data-bs-toggle="button" attribute on page load. The basic markup looks like this:

<!-- button tags -->
<button type="button" class="btn btn-primary" data-bs-toggle="button" autocomplete="off">Toggle button</button>
<button type="button" class="btn btn-primary active" data-bs-toggle="button" autocomplete="off" aria-pressed="true">Active toggle button</button>
<button type="button" class="btn btn-primary" disabled data-bs-toggle="button" autocomplete="off">Disabled toggle button</button>
<!-- anchor tags -->
<a href="#" class="btn btn-primary" role="button" data-bs-toggle="button">Toggle link</a>
<a href="#" class="btn btn-primary active" role="button" data-bs-toggle="button" aria-pressed="true">Active toggle link</a>
<a href="#" class="btn btn-primary disabled" tabindex="-1" aria-disabled="true" role="button" data-bs-toggle="button">Disabled toggle link</a>

Button JavaScript API

If the above markup is present in the DOM when the library is loaded, the component will initialize all targets via DATA API, however if inserted later into the DOM, here's how to initialize it:

// initialize
var myButtonINIT = new BSN.Button('#myButton');

The <button id="myButton"> element is now initialized, you can access the instance object anywhere you need:

// reference the initialization, even for DATA API initialized btn-group elements
var myButtonINIT = BSN.Button.getInstance('#myButton');

Button Examples

State Toggle

Toggle link Active toggle link Disabled toggle link

Checkboxes and Radio

The following examples are purely for demo and only require the proper markup, no script is required.

Carousel

The Carousel component covers the original events, as well as a set of essential options and public methods. In addition it also provides a solid DATA API, it adds a paused class to the target element when in paused state, and a solid event handling implementation.

The component implements a lock mechanism to guard over trigger events making it virtually impossible to break.

Carousel Options

Name Type Default Description
keyboard boolean true Option that allows the user to navigate the carousel with left and right arrow keys. If you want to disable this feature, do that via JavaScript or the data-bs-keyboard="false" attribute.
pause boolean
or
the text 'hover'
'hover' Option that makes possible to pause the carousel transition on mouse hover and touchdown. You can disable this via JavaScript or the data-bs-pause="false" attribute.
touch boolean true Option that enables support for touch events. This option is true by default, but you can disable it via JavaScript or the data-bs-touch="false" attribute.
interval number 5000 Sets the component's delay between transitions in miliseconds. Can be set via JavaScript or the data-bs-interval="INTERVAL" attribute. If you want to disable the automatic transition, you can set this option to false. The component will not automatically slide if the element is not visible in the viewport.

Carousel Methods

instance.cycle()

The method will cycle through items. Using the method while the animation is running will produce no effect.

instance.pause()

The method will pause the automatic cycle of the carousel. To resume, you can use the above .cycle() method.

instance.to()

The method will allow you to jump to the index of a certain item. Using the method while the animation is running will produce no effect.

instance.next()

The method will allow you to jump to the next item. This uses the above .to() method.

instance.prev()

The method will allow you to jump to the previous item. This uses the above .to() method.

instance.dispose()

Removes the component from target element.

Carousel.getInstance()

A static method that allows you to access a Carousel instance associated to a DOM element.

Note The previously featured instance method .getActiveIndex() has been deprecated in favor of custom event properties which provide much more information from the instance execution context.

Carousel Events

The Carousel component exposes two events that allow you to trigger custom functionality when the carousel slides.

Event Type Description
slide.bs.carousel This event fires immediately when the slideTo() instance method is called.
This event can be default prevented.
slid.bs.carousel This event is fired when transition has finished.

These component specific events are triggered on the <div class="carousel"> element and both expose the following additional properties:

Event Property Description
direction The direction the carousel is sliding, either left or right.
from The index of the current active carousel item (integer starting with 0 index).
to The index of the next active carousel item.
relatedTarget The DOM element which is the next active carousel item.

Carousel DATA API

The component covers most of the original implementation in regards to DATA API, except that you can ignore some of the attributes for the controls, but they must have at least their specific class in order to work. This is a basic template markup followed by a complete attributes breakdown:

<!-- the Carousel component -->
<div id="myCarousel" class="carousel slide" data-bs-ride="carousel" data-bs-interval="5000" data-bs-touch="true" data-bs-pause="hover">
  <!-- Indicators -->
  <div class="carousel-indicators">
    <button data-bs-target="#myCarousel" data-bs-slide-to="0" class="active"></button>
    <button data-bs-target="#myCarousel" data-bs-slide-to="1"></button>
    <button data-bs-target="#myCarousel" data-bs-slide-to="2"></button>
  </div>
  <!-- Wrapper for slides -->
  <div class="carousel-inner">
    <div class="carousel-item active">
      <img class="img-fluid" src="..." alt="...">
      <div class="carousel-caption">
      <h3>This is a carousel caption</h3>
      </div>
    </div>
    <div class="carousel-item">
      <img class="img-fluid" src="..." alt="...">
      <div class="carousel-caption">
      <h3>This is a caption</h3>
      </div>
    </div>
    <div class="carousel-item">
      <img class="img-fluid" src="..." alt="...">
      <div class="carousel-caption">
      <h3>This is another caption</h3>
      </div>
    </div>
  </div>

  <!-- Controls -->
  <a class="carousel-control-prev" href="#myCarousel" role="button" data-bs-slide="prev">
    <span class="carousel-control-prev-icon" aria-hidden="true"></span>
    <span class="visually-hidden">Prev</span>
  </a>
  <a class="carousel-control-next" href="#myCarousel" role="button" data-bs-slide="next">
    <span class="carousel-control-next-icon" aria-hidden="true"></span>
    <span class="visually-hidden">Next</span>
  </a>
</div>

Attributes Breakdown

  • id="myCarousel" is only required for controls outside the scope of the element itself;
  • data-bs-ride="carousel" is the attribute required if you want the Carousel component to initialize your element automatically;
  • data-bs-keyboard="false" (not shown in the sample markup) is the attribute that enables navigation via keyboard left and right arrow keys, but only if the target element is visible in the viewport;
  • data-bs-interval="5000" sets the automatic slide interval; the false value will disable automatic slide transition; the usage of this attribute for each item is not implemented in BSN;
  • data-bs-pause="hover" is the attribute you can set to pause the carousel on mouse hover, but it also adds a paused class to your carousel; if the above attribute data-bs-interval is false, this setting has no effect;
  • data-bs-touch="true" is the attribute you can set to enable touch support for your carousel, however, you must have at least 3 .carousel-item elements in order to work;
  • data-bs-slide-to="0" is an attribute used by elements of the .carousel-indicators; when clicked, it will transition to the carousel item with the specified index, which is 0 (zero) in this case;
  • data-bs-slide="prev" / data-bs-slide="next" when clicked, will transition to the next / previous carousel item;
  • data-bs-target="#myCarousel" attribute is required for any of the Carousel controls outside the scope of the carousel element itself and optional for indicators / controls inside;
  • class="carousel-item active" / class="active" when active class is present for a carousel item or indicator, that indicates which carousel item is currently shown to the user.

Right To Left languages

The Carousel component provides support for RTL Languages but the functionality has some specific requirements:

  • first, you need to make sure your markup matches the original library requirements;
  • as is, the component should work out of the box, you may need some additional styling if you choose to use custom icons for the indicators or navigation controls.

Carousel JavaScript API

The component grants full access to the internal working via JavaScript; whether via the public methods or the original events, you can do a whole bunch of things. Assuming the above markup have been injected into the DOM, let's go ahead and initialize it:

// initialize with some options
var myCarouselInit = new BSN.Carousel('#myCarousel', {
  // these options values will override the ones set via DATA API
  interval: false,
  pause: false,
  keyboard: false
});

And now we can play with the methods:

// call next() to jump to the next item
myCarouselInit.next();

// jump to the item with index 2
myCarouselInit.to(2);

// if the carousel was set with `interval: NUMBER`
// call this method to pause the automatic cycle
myCarouselInit.pause();

// if the carousel was set with `interval: false`
// we can do this to go to the next item
// AND resume if `interval: NUMBER` is used
myCarouselInit.cycle();

// anytime you need to destroy
myCarouselInit.dispose();

Additional interaction can be coded around the original events:

// this event handler function will run when the carousel begins to slide
document.querySelector('.carousel').addEventListener('slide.bs.carousel', event => {
  if (event.target.id !== 'myCarousel') {
    event.preventDefault(); // preventDefault for your special case
    return;
  }
  // or do something with the event specific properties
  console.log("The carousel is sliding " + event.direction);
  console.log("The carousel is sliding to index " + event.to);
  console.log("The carousel is sliding from index " + event.from);
});

Access the instance object anywhere, even for instances where the DATA API was used:

// get some carousel item and reference the initialization
var mySpecialCarouselInit = BSN.Carousel.getInstance('#mySpecialCarousel');

// apply methods
mySpecialCarouselInit.cycle();

Carousel Example

This is a test demonstrating the component capabilities and it's original events, you should open the console and start clicking, you will be notified before and after the animation. Also know that there was no active item set by default in the markup, proving the component can successfully manage this case by setting the first item as active on initialization.

These three independent buttons use some inline JavaScript to control the carousel:

<button data-bs-target="#myCarousel" data-bs-slide-to="0" class="btn btn-secondary">
  START
</button>

<button data-bs-target="#myCarousel" data-bs-slide="prev" class="btn btn-secondary">
  PREV
</button>

<button data-bs-target="#myCarousel" data-bs-slide="next" class="btn btn-secondary">
  NEXT
</button>

This highlights the fact that we don't need to use href="#myCarousel" or data-bs-target="#myCarousel" attributes for the controls inside the carousel itself, however if the carousel itself has an ID, these attributes used in the above markup shows you how to easily control it with elements outside the carousel.

Collapse

The Collapse component covers the original events and methods of the jQuery plugin counterpart. This component understands there is a triggering element that finds its target collapsible element via the data-bs-target="#collapse-id" attribute or the href="#collapse-id" attribute if it's a link.

Collapse Options

The option below allow you to connect a collapse to a parent accordion.

Name Type Default Description
parent selector
or
reference
Option to reference a parent to be used as an accordion. When a parent is set and found, it will enable the functionality described in the show() method below. Can be set via JavaScript or the data-bs-parent="SELECTOR" attribute when used for the <div class="collapse"> element.

Collapse Methods

Calling any of the public methods while animation is running, will produce no effect.

instance.show()

The method will expand a collapsible element. In addition, if the collapsible element is part of an accordion (it's options include a reference to a parent), it will also close any other visible collapsible element.

instance.hide()

The method hides a collapsible element.

instance.toggle()

The method will show or hide a collapsible element using the above methods and their full functionalities, based on the visibility state at the time of the call.

instance.dispose()

Removes the component from target element.

Collapse.getInstance()

A static method that allows you to access a Collapse instance associated to a DOM element.

Collapse Events

All the component's events are attached to the collapsible element and not its targeting button / element, with other words, the event.target is the element with the class="collapse" attribute.

Event Type Description
show.bs.collapse This event fires immediately when the show instance method is called.
This event can be default prevented.
shown.bs.collapse This event is fired when a collapse element has been made visible to the user.
hide.bs.collapse This event is fired immediately when the hide method has been called.
This event can be default prevented.
hidden.bs.collapse This event is fired when a collapse element has been hidden from the user.

Collapse DATA API

In the following markup, the component will initialize the two .btn elements with the data-bs-toggle="collapse" attribute, both refferencing the same collapsible element via specific HTMLElement attributes.

<!-- toggle collapse via link with HREF reference -->
<a id="collapseLink" class="btn btn-primary" role="button" aria-expanded="false" aria-controls="collapseExample"
  data-bs-toggle="collapse" href="#collapseExample"> <!-- required DATA API -->
  Link with href
</a>

<!-- AND / OR toggle collapse via button with data-bs-target attribute reference -->
<button id="collapseButton" class="btn btn-primary" type="button" aria-expanded="false" aria-controls="collapseExample"
  data-bs-toggle="collapse" data-bs-target="#collapseExample"> <!-- required DATA API -->
  Button with data-bs-target
</button>

<!-- and the basic collapsible template -->
<div class="collapse" id="collapseExample">
  <div class="card card-body">
    ...
  </div>
</div>

Now if we stack multiple collapsible elements and wrap them into one parent with an ID attribute and / or some helper CSS classes, we can easily create an accordion.

<!-- accordion template -->
<div class="accordion" id="accordionExample">
  <div class="accordion-item">
    <h2 class="accordion-header" id="headingOne">
      <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseOne" aria-expanded="false" aria-controls="collapseOne">
        Accordion Item #1
      </button>
    </h2>
    <div id="collapseOne" class="accordion-collapse collapse" aria-labelledby="headingOne" data-bs-parent="#accordionExample">
      <div class="accordion-body">
        Accordion item 1 content.
      </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" aria-expanded="false" aria-controls="collapseTwo">
        Accordion Item #2
      </button>
    </h2>
    <div id="collapseTwo" class="accordion-collapse collapse" aria-labelledby="headingTwo" data-bs-parent="#accordionExample">
      <div class="accordion-body">
        Accordion item 2 content.
      </div>
    </div>
  </div>
  <div class="accordion-item">
    <h2 class="accordion-header" id="headingThree">
      <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseThree" aria-expanded="false" aria-controls="collapseThree">
        Accordion Item #3
      </button>
    </h2>
    <div id="collapseThree" class="accordion-collapse collapse" aria-labelledby="headingThree" data-bs-parent="#accordionExample">
      <div class="accordion-body">
        Accordion item 3 content.
      </div>
    </div>
  </div>
</div>

Collapse JavaScript API

First, you need to initialize it via JavaScript:

// initialize the component for collapse
var myCollapseInit = new BSN.Collapse('.collapse')

This now enables you to work with the public methods.

// call the show() right away
myCollapseInit.show();

// call the hide() later
myCollapseInit.hide();

// OR call toggle() some other time
myCollapseInit.toggle();

// lastly, destroy when needed
myCollapseInit.dispose();

Also we can attach some listeners to the original events:

// first, we need to reference the collapse element
var myCollapseExample = document.getElementById('#myCollapseExample');

// attach a handler to the `show.bs.collapse` original event
myCollapseExample.addEventListener('show.bs.collapse', (event) => {
  // do something cool when .show() method is called
  // event.target is myCollapseExample
}, false);

Alright, now let's say the above accordion template have been inserted into the DOM, you need to initialize its collapsible elements right away via JavaScript.

// grab the accordion by its ID
var myAccordion = document.getElementById('myAccordion');

// grab the collapse elements of this accordion
var myAccordionCollapses = myAccordion.querySelectorAll('.collapse');

// initialize the component for each collapse trigger
Array.from(myAccordionCollapses).forEach((collapse) => 
  new BSN.Collapse(
    collapse,
    {
      parent: myAccordion
    }
  )
)

The component also allows access to the instance object:

// grab the collapse initialized via DATA API
var myCollapseInit = BSN.Collapse.getInstance('#myCollapse');

// call any public method
myCollapseInit.toggle();

Collapse Examples

Single collapsible element

Here's a quick demo with a single collapsible element, using the .card as the container, exactly as described in the DATA API section. The demo also features the original events.

HREF

Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident.

Accordion / Multiple Collapsible Elements

Here's an Accordion example, built with a dedicated markup from the original plugin. When the toggle links are clicked, our Collapse component will look for the closest <div class="accordion-className"> or <div id="accordion-id"> via data-bs-parent="selector" and will hide any expanded collapse element.

This is the first item's accordion body. It is hidden by default, until the collapse plugin adds the appropriate classes that we use to style each element. These classes control the overall appearance, as well as the showing and hiding via CSS transitions. You can modify any of this with custom CSS or overriding our default variables. It's also worth noting that just about any HTML can go within the .accordion-body, though the transition does limit overflow.

This is the second item's accordion body. It is hidden by default, until the collapse plugin adds the appropriate classes that we use to style each element. These classes control the overall appearance, as well as the showing and hiding via CSS transitions. You can modify any of this with custom CSS or overriding our default variables. It's also worth noting that just about any HTML can go within the .accordion-body, though the transition does limit overflow.

This is the third item's accordion body. It is hidden by default, until the collapse plugin adds the appropriate classes that we use to style each element. These classes control the overall appearance, as well as the showing and hiding via CSS transitions. You can modify any of this with custom CSS or overriding our default variables. It's also worth noting that just about any HTML can go within the .accordion-body, though the transition does limit overflow.

Remember that all triggering buttons must reference the accordion via data-bs-parent="selector" as described above in order to collapse current opened collapsible element.

Dropdown

The Dropdown component covers most of the functionality from the original plugin in terms of original events, instance methods and options, but also offers some additional functionality without using any third party library.

To get on par with the original plugin, our component now features automatic repositioning but without the use of Popper.js, but with PositionObserver to update the menu's position.

Here's how it works:

  • when showing the dropdown menu to the user, the component will calculate all possible positions and update the menu position so that the it's always displayed fully into the viewport;
  • while the dropdown menu is visible to the user, the observer will trigger the update of dropdown menu position, just like when showing it again to the user.

The component supports accessibility features:

  • Up and Down arrow keys will enable users to select menu items, and also when pressed, the event handler will prevent default scroll behavior;
  • Esc key will now close the dropdown, a feature previously supported, but reworked it's keyHandler to support the above new features;
  • Enter key will work as if click event triggered, the new event handler expectes the default browser behavior, let's hope it stays that way;
  • closing the dropdown will now focus the triggering button.

This version of the Dropdown component for Bootstrap 5 no longer supports nesting due to the implementation of automatic repositioning, added RTL Languages support and ES6+ class conversion.

Modal

The Modal component comes with small changes to options, events and public methods when compared to the original plugin. This version is also different from our V4 version as we will explore later on.

In addition to adjusting the spacing (padding) of the <body>, elements like <nav class="navbar fixed-top"> are also adjusted in the same manner to get the smoothest possible transition. Like all components of the library, the component grants access to the initialization object even if your modal is automatically initialized via DATA API.

While shown to the user, the component makes use of ResizeObserver to trigger the update of these elements and not rely on the obsolete implementation of resize event listeners.

Modal Options

Name Type Default Description
backdrop boolean or the string "static" true Includes a modal-backdrop element. Alternatively, specify 'static' for a backdrop which doesn't close the modal on click.
keyboard boolean true Option to dismiss the current modal via Esc key.

The previously featured content option has been deprecated. We decided to allow you to use what ever manipulation method and / or sanitization you consider fit for your projects.

The default options' values are same as their vanilla equivalents so you can expect the same behavior.

Modal Methods

For full control the Modal component exposes a couple of public methods to be used via JavaScript.

instance.show()

The method that shows an initialized modal. When called, it will also hide any other visible modal before showing the one requested, making sure to keep the backdrop in place.

instance.hide()

This hides an initialized modal. Additionally it will also close (if enabled) the backdrop.

instance.toggle()

When called it shows the modal if hidden and hides it otherwise, using one of the above two methods.

instance.update()

This allows you to update the modal layout (handling overflowing/non-overflowing body and/or modal) after layout changes have occured.

instance.dispose()

The method that allows you to remove the modal functionality from a target element. If the modal is shown, this method will close it first by calling the .hide() method before the removal of the functionality.

Modal.getInstance()

A static method that allows you to access a Modal instance associated to a DOM element.

The previously featured .setContent() method has been deprecated.

Modal Events

All original events are triggered for the <div class="modal"> element and not the initialization target with its usual data-bs-toggle="modal" attribute.

Event Type Description
show.bs.modal This event fires immediately when the .show() method is called. If the called came via click and the click target is a modal triggering element, that element is then marked as the event.relatedTarget property of the event object.
This event can be default prevented.
shown.bs.modal This event is fired when the modal has been made visible to the user. The event.relatedTarget is same as for the above.
hide.bs.modal This event is fired immediately when the .hide() instance method has been called. If the click event target is the .btn-close element, that element becomes the event.relatedTarget of this Offcanvas event, however if the click event target is the backdrop, event.relatedTarget will be null.
This event can be default prevented.
hidden.bs.modal This event is fired when the modal has finished being hidden from the user.

If the modal is opened via JavaScript methods, or by clicking on another element that is not a modal triggering element, the event.relatedTarget is null.

In contrast with the original library, BSN doesn't support the hidePrevented.bs.modal event which would require adding one or more additional event listeners just to trigger this event.

Modal DATA API

You can initialize Modal without writing any code as long as you have a modal and a trigger button with the data-bs-target attribute or a link with href attribute referencing that modal. The component will initialize all <div class="modal"> elements found in the DOM.

<!-- provide a trigger button -->
<button data-bs-toggle="modal" data-bs-target="#myModal" type="button">Launch modal</button>

<!-- Alternatively provide a link -->
<a data-bs-toggle="modal" href="#myModal">Launch modal</a>

<!-- also the modal itself -->
<div id="myModal" class="modal fade" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="myModalLabel">Modal title</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        Some content
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
        <button type="button" class="btn btn-success">Save changes</button>
      </div>
    </div>
  </div>
</div>

As shown in the above sample markup, Modal can work with multiple triggering elements as well as multiple dismiss elements, with minimal effort and no events overhead on the global object.

Modal JavaScript API

Generally you can initialize Modal for any instance of <div class="modal"> and immediately get access to methods.

Let's create a very basic modal template for this guide.

<!-- blank modal template -->
<div id="myModal" class="modal fade" tabindex="-1" role="dialog" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">Add your header here</div>
      <div class="modal-body">Add your body content here here</div>
      <div class="modal-footer">Add your footer content here here</div>
    </div>
  </div>
</div>

Next we can initialize this modal and get access to public methods right away:

// initialize on a <div class="modal"> with all options
// Note: options object is optional
var myModalInstance = new BSN.Modal(
  '#myModal', // target selector
  { // options object
    backdrop: 'static', // we don't want to dismiss Modal when Modal or backdrop is the click event target
    keyboard: false // we don't want to dismiss Modal on pressing [Esc] key
  }
);

Keep in mind that re-initializing will make use of the .dispose() method to clear memory allocated for previous initialization, which involves two things: reseting the other options' values to the DATA API specified, or default values AND lastly, if the modal is open, on re-initialization the modal will get hidden via .hide(), you can instantly call the .show() method as written above.

Now we have an initialization reference in myModalInstance, we can start applying the component's public methods:

// show the modal at any time
myModalInstance.show();

// hide the modal
myModalInstance.hide();

// toggle the modal (show/hide)
myModalInstance.toggle();

// if the above method is used while modal was shown, you can then ask for a layout update
myModalInstance.update();

// when initialization is no longer needed, you can destroy it
myModalInstance.dispose();

Any element initialized via DATA API or JavaScript, automatically grants access to the component's original events.

// GET THE EVENT TARGET, THE MODAL
// when we are certain which modal ID to work with
var myModal = document.getElementById('modalID');

// ATTACH listeners
// show.bs.modal event
myModal.addEventListener('show.bs.modal', function(event){
  // do something when this event triggers
  // event.target is the modal referenced in myModal
  // event.relatedTarget is the button referenced with myModalTriggerButton
}, false);

// shown.bs.modal event
myModal.addEventListener('shown.bs.modal', function(event){
  // do something when this event triggers
  // event.target is the modal referenced in myModal
  // event.relatedTarget is the button referenced with myModalTriggerButton
}, false);

// hide.bs.modal event
myModal.addEventListener('hide.bs.modal', function(event){
  // do something when this event triggers
  // event.target is the modal referenced in myModal
}, false);

// hidden.bs.modal event
myModal.addEventListener('hidden.bs.modal', function(event){
  // do something when this event triggers
  // event.target is the modal referenced in myModal
}, false);

Additionally the component will store the initialization object in the modal, for the internal execution, hopefully would help you as well.

// you can access the initialization object from the modal itself
var myModalInit = BSN.Modal.getInstance(myModal);

Modal Examples

Modal Initialized via DATA API

The first example is a modal with static content initialized via DATA API, exactly as described in the above Use via DATA API section, and showcasing the ability to show another modal from a modal currently visible.

Modal Initialized via JavaScript API

The following example is focused on initialization via JavaScript, without a triggering button:

// we grab a modal by ID
var myModal = document.getElementById('myModal');

// we grab some button by ID, we will use it later
var btnModal = document.getElementById('openModalViaJS');
// this button IS NOT a triggering element, it has no reference to the above modal

// initialize Modal for this triggering element
var modalInitJS = new BSN.Modal(myModal, {
  backdrop: 'static'
});

// OR initialize with no options provided
// the options object is optional
var modalInitJS = new BSN.Modal(myModal);

// when we click btnModal, open the modal
btnModal.addEventListener('click', function(e){
  modalInitJS.show();
}, false)

// BONUS
// since there is no triggering element, you might need
// access to the initialization object from another application
var findModalInitJS = BSN.Modal.getInstance(myModal);

As explained in the sample code above, this modal is completely independent from a triggering button which would usually have the data-bs-toggle="modal" and data-bs-target="#myModal" attributes necesary to connect with our modal via DATA API.

Offcanvas

The Offcanvas component is our newest addition and comes packed with options, events and public methods.

Similar to our Modal, this component can also adjust the spacing (padding) of the <body>, and all elements like <nav class="navbar fixed-top"> to get the smoothest possible transition.

Offcanvas Options

Name Type Default Description
backdrop boolean
"static"
true Option to add a backdrop on the body when offcanvas element is shown. Alternatively, specify "static" for a backdrop which doesn't close the offcanvas on click.
keyboard boolean true Option to dismiss the current offcanvas via Esc key.
scroll boolean false Option to allow body scrolling while offcanvas is open.

Offcanvas Methods

For full control the Offcanvas component exposes a couple of public methods to be used via JavaScript :

instance.show()

The method that shows an initialized offcanvas. When called, it will also hide any other visible offcanvas before showing the one requested, making sure to keep track on the backdrop for each offcanvas instance.

instance.hide()

This hides an initialized offcanvas. Additionally it will also remove (if enabled) the backdrop.

instance.toggle()

When called it shows the offcanvas if hidden and hides it otherwise, using one of the above two methods.

instance.update()

This allows you to update the offcanvas layout (handling overflowing/non-overflowing body and/or offcanvas) after you have changed it's content or other layout changes occured.

instance.dispose()

The method that allows you to remove the offcanvas functionality from a target element. If the offcanvas is shown, this method will close it first by calling the .hide() method before the removal of the functionality.

Offcanvas.getInstance()

A static method that allows you to access a Offcanvas instance associated to a DOM element.

Offcanvas Events

All original events are triggered for the <div class="offcanvas"> element.

Event Type Description
show.bs.offcanvas This event fires immediately when the .show() method is called. If the call came via click and the click target is an offcanvas trigger element, that element is then assigned as the event.relatedTarget property of the event object.
This event can be default prevented.
shown.bs.offcanvas This event is fired when the offcanvas has been made visible to the user. The event.relatedTarget is same as for the above.
hide.bs.offcanvas This event is fired immediately when the .hide() instance method has been called. If the method is call came via click and the click target is a dismiss element, that element is then assigned as the event.relatedTarget of this event. If the click event target is the backdrop, event.relatedTarget is null.
This event can be default prevented.
hidden.bs.offcanvas This event is fired when the offcanvas has finished being hidden from the user. This event inherits the event.relatedTarget from the above event.

Similar to the Modal component, if the offcanvas is opened/closed via JavaScript methods, or is dismissed by clicking on another element outside the offcanvas, the event.relatedTarget is null. Also the Offcanvas component doesn't support the hidePrevented.bs.offcanvas event for the exact same reason as for the Modal component.

Offcanvas DATA API

You can initialize Offcanvas without writing any code as long as you have an offcanvas and a trigger button with the data-bs-target attribute or a link with href referencing that offcanvas. The component will initialize all <div class="offcanvas"> elements found in the DOM.

<!-- provide a trigger button -->
<button class="btn btn-primary" type="button" data-bs-toggle="offcanvas" data-bs-target="#offcanvasExample" aria-controls="offcanvasExample">
  Button with data-bs-target
</button>

<!-- or an anchor link -->
<a class="btn btn-primary" data-bs-toggle="offcanvas" href="#offcanvasExample" role="button" aria-controls="offcanvasExample">
  Link with href
</a>

<!-- also the offcanvas itself -->
<div class="offcanvas offcanvas-start" tabindex="-1" id="offcanvasExample" aria-labelledby="offcanvasExampleLabel">
  <div class="offcanvas-header">
    <h5 class="offcanvas-title" id="offcanvasExampleLabel">Offcanvas</h5>
    <button type="button" class="btn-close text-reset" data-bs-dismiss="offcanvas" aria-label="Close"></button>
  </div>
  <div class="offcanvas-body">
    <p>Some text here should work.</p>
  </div>
</div>

Offcanvas JavaScript API

Generally you can initialize Offcanvas for any instance of <div class="offcanvas"> and immediately get access to methods. Similar to our Modal, this component can also work with multiple triggering button elements having the data-bs-toggle="offcanvas" attribute.

Considering the sample markup showcased in the above section, we can now initialize this offcanvas and get access to public methods right away:

// initialize on a <div class="offcanvas"> with all options
var myOffcanvasInstance = new BSN.Offcanvas(
  '#myOffcanvas', // target selector
  { // options object
    backdrop: false, // we don't want to use the backdrop
    keyboard: false, // we don't want to dismiss Offcanvas on pressing [Esc] key
    scroll: true // we allow the user to scroll the page
  }
);

Now we have an initialization reference in myOffcanvasInstance, we can start calling the component's public methods:

// show the offcanvas at any time
myOffcanvasInstance.show();

// hide the offcanvas
myOffcanvasInstance.hide();

// toggle the offcanvas (show/hide)
myOffcanvasInstance.toggle();

// if the above method is used while offcanvas was shown, you can then ask for a layout update
myOffcanvasInstance.update();

// when initialization is no longer needed, you can destroy it
myOffcanvasInstance.dispose();

Any element initialized via DATA API or JavaScript, automatically grants access to the component's original events.

// GET THE EVENT TARGET
// when we are certain which offcanvas ID to work with
var myOffcanvas = document.getElementById('offcanvasID');

// ATTACH listeners
// show.bs.offcanvas event
myOffcanvas.addEventListener('show.bs.offcanvas', function(event){
  // do something when this event triggers
  // event.target is the offcanvas referenced in myOffcanvas
  // event.relatedTarget can be the triggering button or NULL
}, false);

// shown.bs.offcanvas event
myOffcanvas.addEventListener('shown.bs.offcanvas', function(event){
  // do something when this event triggers
  // event.target is the offcanvas referenced in myOffcanvas
  // event.relatedTarget can be the triggering button or NULL
}, false);

// hide.bs.offcanvas event
myOffcanvas.addEventListener('hide.bs.offcanvas', function(event){
  // do something when this event triggers
  // event.target is the offcanvas referenced in myOffcanvas
  // event.relatedTarget can be the triggering/dismiss button or NULL
}, false);

// hidden.bs.offcanvas event
myOffcanvas.addEventListener('hidden.bs.offcanvas', function(event){
  // do something when this event triggers
  // event.target is the offcanvas referenced in myOffcanvas
  // event.relatedTarget can be the triggering/dismiss button or NULL
}, false);

Additionally the component will store the initialization object in the offcanvas, for the internal execution, hopefully would help you as well.

// you can access the initialization object from the offcanvas itself
var myOffcanvasInit = BSN.Offcanvas.getInstance(myOffcanvas);

Offcanvas Examples

These examples are all initialized via DATA API, exactly as described in the above Use via DATA API section, and showcasing the ability to show another offcanvas from an offcanvas currently visible.

Link with href
Offcanvas

This Offcanvas instance has its specific events attached. Check the console for logs.

Opening another Offcanvas instance will close this Offcanvas instance.

SVG Demo Tooltip for IMG
Offcanvas with scrolling

Try scrolling the rest of the page to see this option in action.

SVG Demo Tooltip for IMG
Offcanvas Top

This offcanvas instance uses "static" backdrop.

SVG Demo Tooltip for IMG
Offcanvas with Modal

Opening a Modal instance will close this Offcanvas instance.

This Offcanvas uses data-bs-backdrop="false" intentionally to test the option independently for each instance.

Open Modal SVG Demo Tooltip for IMG
Backdroped with scrolling

Try scrolling the rest of the page to see this option in action.

SVG Demo Tooltip for IMG

Popover

The Popover component will initialize all elements with the data-bs-toggle="popover" attribute. Unlike our previous versions, this component now extends the Tooltip component since both share the same utilities and functionality except that Popover has a different template and the ability to change how events are handled via additional options.

Our implementation can automatically reposition your popovers when showing them to the user, as well as when a popover is visible and layout changes, our new PositionObserver will trigger the update instead of the previously implemented resize and scroll event listeners.

On that note, Popover makes use of some floating-ui functionality which have been gradually implemented into our component to always provide an accurate popover position.

The Popover implements a special lock mechanism to make it virtually impossible to break if the user decides to spam trigger events.

Popover Options

The component covers all needed options, including those for a template system:

Name Type Default Description
animation boolean true Option to enable/disable the popover animation. If you disable the animation, you can do that via the data-bs-animation="false" attribute. When enabled, this option will add an additional CSS class fade to the popover to enable the transition.
btnClose string
HTMLElement
markup (see description) Option to set a custom close button for dismissible popovers. This option is useful for labelling the button for WAI-ARIA compliant and multi-language applications as well as for using custom icons. The default button markup is:
<button class="btn-close" aria-label="Close"></button>
This option allows you to set an HTMLElement to be cloned and used as the dismiss button.
This option is JavaScript API only.
content string
HTMLElement
Option to set the content of the popover via JavaScript or the data-bs-content="CONTENT" attribute. You can also specify a DOM node to serve as your popover content. This option is required via DATA API initialization or JavaScript initialization in order to validate.
This option allows you to set an HTMLElement to be cloned and used as the content filler for your Popover.
customClass string Option to customize the popover by adding a custom CSS class. You can set this option via the data-bs-custom-class="my-class" attribute.
delay number 200 A short delay before hiding the popover.
Can be set via JavaScript or the data-bs-delay="DELAY" attribute.
dismissible boolean false Option to make the popover dismissible. When true, it will also add an × button at the top-right of the popover. You can enable this option via JavaScript API or the data-bs-dismissible="true" attribute.
placement string top Option to set a specific placement to top, bottom, left or right, relative to it's target. Can be set via both JavaScript and the data-bs-placement="POSITION" attribute.
sanitizeFn function null Option to set a function that will sanitize the title, content, template and the dismissing <button class=btn-close"> element. Our library doesn't include any sanitization function, you are free to use whatever solution suits your need.
This option is JavaScript API only.
template string markup (see description) Option to use a custom HTML template for your popover initialization. You can also specify a DOM node to serve as your template. The following markup is the default template:
'<div class="popover" role="tooltip">
  <div class="popover-arrow"></div>
  <h3 class="popover-header"></h3>
  <div class="popover-body"></div>
</div>'

The contents from the title option or the data-bs-title attribute will fill in the template's .popover-header element, while the contents of the data-bs-content attribute will fill in the .popover-body element.
This option allows you to set an HTMLElement to be cloned and used as the template for your Popover.
This option is JavaScript API only.
title string | HTMLElement Option to set the title of the popover via JavaScript or the data-bs-title="TITLE" attribute. You can also specify a DOM node to serve as your popover title.
This option allows you to set an HTMLElement to be cloned and used as the title filler for your Popover.
trigger string hover focus Option to change the component's trigger event: manual, hover, focus, click or any combination separated via space, except that manual cannot be combined.
* manual - makes the popover get shown/hidden only via the .show(), .hide() or .toggle() methods, programmed by the developer with own scripting;
* click - will toggle the popover visibility when click event is triggered by the user, however when the above option dismissible is true, the user can only dismiss the popover by clicking the <button class="btn-close"> element.
* hover - will attach mouseenter and mouseleave event listeners to show / hide the popover with a similar interaction when dismissible option is true;
* focus - will attach focusin and focusout event listeners to show / hide the popover, also taking into account the dismissible option; in some cases you may want to open a popover only on focus for form elements or click for other HTMLElement items.
You can set this option value via JavaScript or the data-bs-trigger="EVENT(S)" attribute.

The Popover component no longer requires the container option

If a proper template is not specified via JavaScript or the content option is not set in any way, the Popover will not be initialized for that specific element.

When your popover title and/or content are HTML markup strings, remember to sanitize the content of the markup.

Popover Methods

For full control the Popover component exposes a couple of public methods to be used via JavaScript.

instance.show()

The method shows an initialized popover. When the method is called, it will always create a new popover and append it into your designated container.

instance.hide()

The method hides an initialized popover and remove it from its container and also from the memory, as if you would automatically destroy it.

instance.toggle()

The method shows the popover if hidden and hides it otherwise, using the above two methods.

instance.enable()

Starts showing the popover again to the user. Popovers are enabled by default.

instance.disable()

Stops showing the popover to the user.

instance.toggleEnabled()

Toggles the enabled state by calling one of the two methods above.

instance.update()

Updates the position of the popover.

instance.handleTouch()

The event listener for touch enabled devices.

instance.dispose()

Removes the component from target element.

Popover.getInstance()

A static method that allows you to access a Popover instance associated to a DOM element.

Popover Events

The component's original events are same as with the original jQuery Plugin, except inserted.bs.popover, just as explained for the Tooltip component.

The event.target of the original events is the the initialization target with the data-bs-toggle="popover" attribute.

Event Type Description
show.bs.popover This event fires immediately when the show instance method is called.
This event can be default prevented.
shown.bs.popover This event is fired when the popover has been made visible to the user.
hide.bs.popover This event is fired immediately when the hide instance method has been called.
This event can be default prevented.
hidden.bs.popover This event is fired when the popover has finished being hidden from the user.
updated.bs.popover This event is fired after the popover has updated it's position.

Popover DATA API

Our component will initialize any element found to have the data-bs-toggle="popover" attribute and at least the data-bs-content attribute.

<!-- any regular link with data-bs-toggle="popover" -->
<a href="https://google.com" data-bs-title="Google" data-bs-content="Google is cool" data-bs-toggle="popover">Google</a>

<!-- any SVG shape with data-bs-toggle="popover" -->
<svg viewBox="0 0 80 34" width="80" height="34" xmlns="http://www.w3.org/2000/svg">
  <rect data-bs-toggle="popover" data-bs-placement="top" data-bs-delay="150" data-bs-content="Demo Title for SVG" rx="5"></rect>
</svg>

Popover JavaScript API

After inserting new content into the page, you can initialize any element with Popover via JavaScript. You can also initialize for elements not having the specific DATA API. You can do the following:

// find all elements with data-bs-content attribute
var popoverTargets = document.querySelectorAll('[data-bs-content]'); // also a certain class would go fine

// initialize Popover for each element
Array.from(popoverTargets).forEach(
  popTarget => new BSN.Popover( popTarget, {
    placement: 'top', // string
    animation: true, // boolean
    customClass: 'my-special-class', // string
    delay: 100, // integer
    dismissible: true, // boolean
    btnClose: '<button class="btn-close" aria-label="Close"></button>', // string
    sanitizeFn: function(dirty){ // use sanitizer of your choice here
      return DOMPurify.sanitize(dirty);
    }    
  })
);

In addition, similar to any other component of this library, you can access the initialization and the public methods even for elements initialized via DATA API.

// find an element initialized with Popover
var myLinkWithPopover = document.getElementById('myLinkWithPopover');

// reference the initialization object
var myPopoverInit = BSN.Popover.getInstance(myLinkWithPopover);

Just because you can, you can re-initialize any element on the fly, to change options or to just call the .show() method.

// re-initialize Popover and call .show()
new BSN.Popover('#selector',options).show();

Considering the just above element, let's go ahead and put the component's events to use:

// show.bs.popover
myLinkWithPopover.addEventListener('show.bs.popover', function(event){
  // do some cool stuff when .show() method is called
  // event.target is myLinkWithPopover
}, false);

// shown.bs.popover
myLinkWithPopover.addEventListener('shown.bs.popover', function(event){
  // do some cool stuff when .show() method completed
  // event.target is myLinkWithPopover
}, false);

// hide.bs.popover
myLinkWithPopover.addEventListener('hide.bs.popover', function(event){
  // do some cool stuff when .hide() method is called
  // event.target is myLinkWithPopover
}, false);

// hidden.bs.popover
myLinkWithPopover.addEventListener('hidden.bs.popover', function(event){
  // do some cool stuff when .hide() method completed
  // event.target is myLinkWithPopover
}, false);

To use the template system, you can do the following:

// initialize Popover with a custom template
var popover2 = new BSN.Popover('.popover-via-template', { // where .popover-via-template is the text input
  title: 'Sample title', // string
  content: '<p>Some sample message.</p>', // string
  trigger: 'focus', // string
  sanitizeFn: yourUtilityOfChoice, // function
  template: '<div class="popover custom-class" role="tooltip">'
  + '<div class="arrow"></div>'
  + '<h3 class="popover-header"></h3>'
  + '<div class="popover-body"></div>'
  + '</div>'
});

Popover Examples

First let's test all the placement positions, we start with inline links having the bottom placement, then left, and right.

Now we are going to test buttons with a popover with large contents. The last two examples below are using the template system and different trigger options. The popover generated for the last two examples can be dismissed on window resize or blur (focus out).

SVG Demo Popover for IMG

This is an a <div class="position-relative"> parent element to hold two position-absolute elements with Popover.

SVG Demo Popover for IMG

Scrollspy

The ScrollSpy component inherits most of the layout and other requirements from the original component. This component offers public methods, the specific original event, and provides rich JavaScript and DATA APIs.

The component will initialize for each element with data-bs-spy="scroll" attribute, but will not work if the above requirements are not met or the anchors don't reference the containers accordingly. In addition, the component will handle click to enable smooth scroll for your targets by default without any additional options.

This implementation uses the PositionObserver which is responsible for triggering the update of the menu items instead of the previously inneficient resize and scroll event listeners.

ScrollSpy Options

Name Type Default Description
target string
or a
reference
element '#ID'
or other reference
The option to target the container with data-bs-spy="scroll" attribute.
EG: data-bs-target="#myMenuID"
offset - - This option has been removed in BSN v5.1.

ScrollSpy Methods

instance.refresh()

When DOM layout changes occured without triggering a resize of your element, you will have this option to immediately update the status of your menu items.

instance.dispose()

Removes the component from target element.

ScrollSpy.getInstance()

A static method that allows you to access a ScrollSpy instance associated to a DOM element.

ScrollSpy Events

The event.target is the element we initialized the component via JavaScript or has the data-bs-spy="scroll" attribute. The newly activated menu item is the event.relatedTarget of the event object.

Event Type Description
activate.bs.scrollspy This event fires whenever a new item was activated by the component. The event.relatedTarget is the newly activated list/menu item.

ScrollSpy DATA API

To initialize ScrollSpy, remember the requirements from the original jQuery plugin. The component can initialize any element with overflow: auto|scroll and a fixed height, or the <body> or an immediate child element. For the second case we need some special HTML markup and appropriate styling for containers in order to initialize.

An overflowing element that has set overflow: auto|scroll style rule:

  • The headings have the required IDs;
  • Only the element requires some additional CSS;
  • No special markup required.
<!-- the element we initialize ScrollSpy on -->
<div data-bs-spy="scroll" data-bs-target="#navbar-example" class="scrollspy-example">

  <!-- we look for the position of heading -->
  <h4 id="one">Title ONE</h4>
  <p>Valid TEXT goes here</p>

  <h4 id="twoOne">Title TWO</h4>
  <p>Valid TEXT goes here</p>

  <h4 id="three">Title THREE</h4>
  <p>Valid TEXT goes here</p>

</div>

<!-- we need a target, any of the below elements with an ID will do -->
<nav id="nav-example"> <!-- we can also target it's parent as well -->
  <ul id="navbar-example" class="nav flex-column"> <!-- this is our element's target -->
    <li class="nav-item"><a class="nav-link" href="#one">One</a></li>
    <li class="nav-item"><a class="nav-link" href="#two">Two</a></li>
    <li class="nav-item"><a class="nav-link" href="#three">Three</a></li>
  </ul>
</nav>

In this case we only need to set a fixed height for the element and change its overflow:

/* the element we initialize ScrollSpy on */
.scrollspy-example {
  position: relative; /* required */
  height: 150px; overflow: auto; /* required: height must be px based, and overflow: scroll/auto */
}

A non-overflowing element that wraps most of the content of your page:

  • Special markup IS required;
  • The element's child containers have the required IDs;
  • Child containers require some additional styling.
<!-- the element we initialize ScrollSpy on -->
<div data-bs-spy="scroll" data-bs-target="#navbar-example" class="scrollspy-example">

<section id="one"> <!-- this is a ScrollSpy container -->
  Valid HTML goes here
</section>

<section id="two">
  <section id="twoone">
    One level nested containers also apply
  </section>

  <section id="twotwo">
    This is your second nested container
  </section>
</section>

</div>

<!-- we need a target, any of the below elements with an ID will do -->
<nav> <!-- we can also target it's parent as well -->
<ul id="myScrollSpyTarget" class="nav flex-column"> <!-- this is our element's target -->
  <li class="nav-item"><a href="#one">One</a></li>
  <li class="nav-item">
    <a class="nav-link" href="#two">Two</a>
    <ul class="nav flex-column">
      <li class="nav-item"><a class="nav-link" href="#twoone">Two One</a></li>
      <li class="nav-item"><a class="nav-link" href="#twotwo">Two Two</a></li>
    </ul>
  </li>
</ul>
</nav>

ScrollSpy JavaScript API

For full control and access to the component's features, coding the JavaScript part is a breeze. Assuming the above markup have been injected into the DOM and the CSS is set, let's initialize, apply the public method and attach listeners to the original event.

// the element we initialize ScrollSpy on
var myScrollSpyElement = document.getElementsByClassName('scrollspy-example')[0];

// let's give the initialization a JavaScript reference for the "target" option
var myScrollSpyTarget = document.getElementById('myScrollSpyTarget');

// initialize the ScrollSpy for this element
var myScrollSpyInit = new BSN.ScrollSpy(myScrollSpyElement, {
  // set options
  target : myScrollSpyTarget,
  // alternativelly, provide a valid selector string
  // EG: ".my-unique-class-name" or "#my-unique-ID"

  // in some cases the offset option would help calculate
  // the correct boundaries of target containers
  offset: 15
})

If the initialization validates (the target option is valid and the component links the element with it's target), we have access to the methods and the original event.

// apply the public method after DOM changed
// a new element container and it's corresponding menu item have been injected into the DOM
myScrollSpyInit.refresh();

// attach an event handler
myScrollSpyElement.addEventListener('activate.bs.scrollspy', function(event){
  // do some cool stuff
  // event.target is myScrollSpyElement
  // event.relatedTarget is the menu item link that triggered the event
}, false);

// when no longer needed, destroy
myScrollSpyInit.dispose();

To get access to an initialization object regardless of how it was initialized, here's how to do it:

// grab an element we know it was initialized via DATA API
var myScrollSpy = document.getElementById('myScrollSpy');

// get the instance
var myScrollSpyInit = BSN.ScrollSpy.getInstance(myScrollSpy);

// call the public methods
myScrollSpyInit.refresh();
// or
myScrollSpyInit.dispose();

Now this makes alot more sense, especially when you expect full control and also want to make sure you don't attach event listeners multiple times for your elements.

ScrollSpy Examples

According to the above Usage Guide let's initialize an overflowing element via DATA API:

Tumblr farm

Ad leggings keytar, brunch id art party dolor labore. Pitchfork yr enim lo-fi before they sold out qui. Tumblr farm-to-table bicycle rights whatever. Anim keffiyeh carles cardigan. Velit seitan mcsweeney's photo booth 3 wolf moon irure. Cosby sweater lomo jean shorts, williamsburg hoodie minim qui you probably haven't heard of them et cardigan trust fund culpa biodiesel wes anderson aesthetic. Nihil tattooed accusamus, cred irony biodiesel keffiyeh artisan ullamco consequat.

Carles aesthetic

Veniam marfa mustache skateboard, adipisicing fugiat velit pitchfork beard. Freegan beard aliqua cupidatat mcsweeney's vero. Cupidatat four loko nisi, ea helvetica nulla carles. Tattooed cosby sweater food truck, mcsweeney's quis non freegan vinyl. Lo-fi wes anderson +1 sartorial. Carles non aesthetic exercitation quis gentrify. Brooklyn adipisicing craft beer vice keytar deserunt.

one

Occaecat commodo aliqua delectus. Fap craft beer deserunt skateboard ea. Lomo bicycle rights adipisicing banh mi, velit ea sunt next level locavore single-origin coffee in magna veniam. High life id vinyl, echo park consequat quis aliquip banh mi pitchfork. Vero VHS est adipisicing. Consectetur nisi DIY minim messenger bag. Cred ex in, sustainable delectus consectetur fanny pack iphone.

two

In incididunt echo park, officia deserunt mcsweeney's proident master cleanse thundercats sapiente veniam. Excepteur VHS elit, proident shoreditch +1 biodiesel laborum craft beer. Single-origin coffee wayfarers irure four loko, cupidatat terry richardson master cleanse. Assumenda you probably haven't heard of them art party fanny pack, tattooed nulla cardigan tempor ad. Proident wolf nesciunt sartorial keffiyeh eu banh mi sustainable. Elit wolf voluptate, lo-fi ea portland before they sold out four loko. Locavore enim nostrud mlkshk brooklyn nesciunt.

three

Ad leggings keytar, brunch id art party dolor labore. Pitchfork yr enim lo-fi before they sold out qui. Tumblr farm-to-table bicycle rights whatever. Anim keffiyeh carles cardigan.

For this example the overflowing element itself is the target of the scroll event, and above it the .nav component as it's target, while for the other example in this page, the side navigation on the right side, the window is the target of the scroll event.

Bonus Example

Item 1

Ex consequat commodo adipisicing exercitation aute excepteur occaecat ullamco duis aliqua id magna ullamco eu. Do aute ipsum ipsum ullamco cillum consectetur ut et aute consectetur labore. Fugiat laborum incididunt tempor eu consequat enim dolore proident. Qui laborum do non excepteur nulla magna eiusmod consectetur in. Aliqua et aliqua officia quis et incididunt voluptate non anim reprehenderit adipisicing dolore ut consequat deserunt mollit dolore. Aliquip nulla enim veniam non fugiat id cupidatat nulla elit cupidatat commodo velit ut eiusmod cupidatat elit dolore.

Item 1-1

Amet tempor mollit aliquip pariatur excepteur commodo do ea cillum commodo Lorem et occaecat elit qui et. Aliquip labore ex ex esse voluptate occaecat Lorem ullamco deserunt. Aliqua cillum excepteur irure consequat id quis ea. Sit proident ullamco aute magna pariatur nostrud labore. Reprehenderit aliqua commodo eiusmod aliquip est do duis amet proident magna consectetur consequat eu commodo fugiat non quis. Enim aliquip exercitation ullamco adipisicing voluptate excepteur minim exercitation minim minim commodo adipisicing exercitation officia nisi adipisicing. Anim id duis qui consequat labore adipisicing sint dolor elit cillum anim et fugiat.

Item 1-2

Cillum nisi deserunt magna eiusmod qui eiusmod velit voluptate pariatur laborum sunt enim. Irure laboris mollit consequat incididunt sint et culpa culpa incididunt adipisicing magna magna occaecat. Nulla ipsum cillum eiusmod sint elit excepteur ea labore enim consectetur in labore anim. Proident ullamco ipsum esse elit ut Lorem eiusmod dolor et eiusmod. Anim occaecat nulla in non consequat eiusmod velit incididunt.

Item 2

Quis magna Lorem anim amet ipsum do mollit sit cillum voluptate ex nulla tempor. Laborum consequat non elit enim exercitation cillum aliqua consequat id aliqua. Esse ex consectetur mollit voluptate est in duis laboris ad sit ipsum anim Lorem. Incididunt veniam velit elit elit veniam Lorem aliqua quis ullamco deserunt sit enim elit aliqua esse irure. Laborum nisi sit est tempor laborum mollit labore officia laborum excepteur commodo non commodo dolor excepteur commodo. Ipsum fugiat ex est consectetur ipsum commodo tempor sunt in proident.

Item 3

Quis anim sit do amet fugiat dolor velit sit ea ea do reprehenderit culpa duis. Nostrud aliqua ipsum fugiat minim proident occaecat excepteur aliquip culpa aute tempor reprehenderit. Deserunt tempor mollit elit ex pariatur dolore velit fugiat mollit culpa irure ullamco est ex ullamco excepteur.

Item 3-1

Deserunt quis elit Lorem eiusmod amet enim enim amet minim Lorem proident nostrud. Ea id dolore anim exercitation aute fugiat labore voluptate cillum do laboris labore. Ex velit exercitation nisi enim labore reprehenderit labore nostrud ut ut. Esse officia sunt duis aliquip ullamco tempor eiusmod deserunt irure nostrud irure. Ullamco proident veniam laboris ea consectetur magna sunt ex exercitation aliquip minim enim culpa occaecat exercitation. Est tempor excepteur aliquip laborum consequat do deserunt laborum esse eiusmod irure proident ipsum esse qui.

Item 3-2

Labore sit culpa commodo elit adipisicing sit aliquip elit proident voluptate minim mollit nostrud aute reprehenderit do. Mollit excepteur eu Lorem ipsum anim commodo sint labore Lorem in exercitation velit incididunt. Occaecat consectetur nisi in occaecat proident minim enim sunt reprehenderit exercitation cupidatat et do officia. Aliquip consequat ad labore labore mollit ut amet. Sit pariatur tempor proident in veniam culpa aliqua excepteur elit magna fugiat eiusmod amet officia.

If the initialization element is hidden or its height is 0, the ScrollSpy component will attach the scroll listener to the window, basically an invalid instance. Be sure to check the original plugin for other guides or to compare implementations.

Tab

The Tab component covers all original jQuery plugin functionality and even comes with new features such as being able to work with any kind of navigation components in Bootstrap, or providing support for height animation as you can see in the example below.

The component can initialize both via JavaScript and the DATA API, covers the original events and exposes a specific public method, but in contrast to the original plugin it offers some options for you to play with.

Tab Options

To optimize the component and simplify the script, the previously featured initialization option height has been deprecated. The component will always create a height transition for the <div class="tab-content"> element.

Tab Methods

instance.show()

The public method to switch to a certain tab of your choice via JavaScript. If that tab is already visible / active or the method is called while animation is running, the call has no effect.

instance.dispose()

Removes the component from target element.

Tab.getInstance()

A static method that allows you to access a Tab instance associated to a DOM element.

Tab Events

The event.target for the component original events is either the current active tab or the next tab to be activated, depending on the specific event, as explained below. The events will fire in the exact order shown in table below:

Event Type Description
hide.bs.tab This event fires when a new tab is to be shown (and thus the previous active tab is to be hidden). The event.target is the current active tab, while event.relatedTarget is the new soon-to-be-active tab.
This event can be default prevented.
show.bs.tab This event fires on tab show, but before the new tab has been shown. The event.target is the tab next to become active and event.relatedTarget is the current active tab (if available).
This event can be default prevented.
hidden.bs.tab This event fires after a new tab is shown (and thus the previous active tab is hidden). The event.target is the tab that just became inactive and event.relatedTarget is the new active tab.
shown.bs.tab This event fires on tab show after a tab has been shown. The event.target is the new active tab and event.relatedTarget is the previous active tab (if available).

Tab DATA API

Here is a sample markup to showcase the usage of the component with the above mentioned methods. As you can see, each of the elements with the data-bs-toggle="tab" attribute are subject to the Tab component initialization.

<!-- for better usage, wrap the tabs and contents -->
<div id="myTabsWrapper">

<!-- Nav tabs -->
<ul id="myTabs" class="nav nav-tabs" role="tablist">
  <li class="nav-item">
    <a class="nav-link active" id="home-tab" href="#home" data-bs-toggle="tab" data-height="true" aria-controls="home" aria-selected="true" role="tab">Home</a>
  </li>
  <li class="nav-item">
    <a class="nav-link" id="profile-tab" href="#profile" data-bs-toggle="tab" data-height="true" aria-controls="profile" aria-selected="false" role="tab">Profile</a>
  </li>
  <li class="nav-item">
    <a class="nav-link" id="messages-tab" href="#messages" data-bs-toggle="tab" data-height="true" aria-controls="messages" aria-selected="false" role="tab">Messages</a>
  </li>
  <li class="nav-item">
    <a class="nav-link" id="settings-tab" href="#settings" data-bs-toggle="tab" data-height="true" aria-controls="settings" aria-selected="false" role="tab">Settings</a>
  </li>
</ul>

<!-- Tab panes -->
<div class="tab-content">
  <div role="tabpanel" class="tab-pane fade active show" aria-labelledby="home-tab" id="home">...</div>
  <div role="tabpanel" class="tab-pane fade" aria-labelledby="profile-tab" id="profile">...</div>
  <div role="tabpanel" class="tab-pane fade" aria-labelledby="messages-tab" id="messages">...</div>
  <div role="tabpanel" class="tab-pane fade" aria-labelledby="settings-tab" id="settings">...</div>
</div>

</div>

Also don't forget that this functionality works on CSS3 enabled browsers with the Collapse styling in place.

Tab JavaScript API

Since the component will target a single element with / or without data-bs-toggle="tab" attribute, but at least it references a corresponding tab via href or data-bs-target, we will need to do a simple loop to initialize multiple elements. Assuming the above markup have been injected into the DOM, let's initialize, use the public method and attach listeners to the original events.

// first, we reference the .nav component that holds all tabs
var myTabs = document.getElementById('myTabs');

// let's give the initialization a JavaScript reference for the "target" option
var myTabsCollection = myTabs.getElementsByTagName('A');

// initialize the component for all items in the collection
Array.from(myTabsCollection).forEach(
  tab => new BSN.Tab( tab )
);

If each item in the collection meets the expected markup and the tab it referencing is found, the initialization will then validate and give you immediate access to method.

// get last item from collection and reference it's initialization
var myLastTab = myTabsCollection[myTabsCollection.length-1];
var myLastTabInit = BSN.Tab.getInstance(myLastTab);

// assuming the last tab is not active, we can show it
myLastTabInit.show();

// attach an event handler as well
myLastTab.addEventListener('show.bs.tab', function(event){
  // do some cool stuff
  // event.target is myLastTab
  // event.relatedTarget is the previous active tab
}, false);

We could have also built an Object / Array with the initialization objects, but that depends very much on your needs.

Tab Examples

OK now we're ready to put this component to the test. We'll use all Bootstrap .nav components in the pool.

These tabs have no active tab on initialization. Nesciunt tofu stumptown aliqua, retro synth master cleanse. Mustache cliche tempor, williamsburg carles vegan helvetica.

Reprehenderit butcher retro keffiyeh dreamcatcher synth. Cosby sweater eu banh mi, qui irure terry richardson ex squid. Aliquip placeat salvia cillum iphone. Seitan aliquip quis cardigan american apparel, butcher voluptate nisi qui.

This tab have no animation. Food truck fixie locavore, accusamus mcsweeney's marfa nulla single-origin coffee squid. Exercitation +1 labore velit, blog sartorial PBR leggings next level wes anderson artisan four loko farm-to-table craft beer twee. Qui photo booth letterpress, commodo enim craft beer mlkshk aliquip jean shorts ullamco ad vinyl cillum PBR.

Homo nostrud organic, assumenda labore aesthetic magna delectus mollit. Keytar helvetica VHS salvia yr, vero magna velit sapiente labore stumptown. Vegan fanny pack odio cillum wes anderson 8-bit, sustainable jean shorts beard ut DIY ethical culpa terry richardson biodiesel. Art party scenester stumptown, tumblr butcher vero sint qui sapiente accusamus tattooed echo park.

These tabs have no animation Raw denim you probably haven't heard of them jean shorts Austin. Nesciunt tofu stumptown aliqua, retro synth master cleanse. Mustache cliche tempor, williamsburg carles vegan helvetica.

Reprehenderit butcher retro keffiyeh dreamcatcher synth. Cosby sweater eu banh mi, qui irure terry richardson ex squid. Aliquip placeat salvia cillum iphone. Seitan aliquip quis cardigan american apparel, butcher voluptate nisi qui.

Food truck fixie locavore, accusamus mcsweeney's marfa nulla single-origin coffee squid. Exercitation +1 labore velit, blog sartorial PBR leggings next level wes anderson artisan four loko farm-to-table craft beer twee. Qui photo booth letterpress, commodo enim craft beer mlkshk aliquip jean shorts ullamco ad vinyl cillum PBR.

Homo nostrud organic, assumenda labore aesthetic magna delectus mollit. Keytar helvetica VHS salvia yr, vero magna velit sapiente labore stumptown. Vegan fanny pack odio cillum wes anderson 8-bit, sustainable jean shorts beard ut DIY ethical culpa terry richardson biodiesel. Art party scenester stumptown, tumblr butcher vero sint qui sapiente accusamus tattooed echo park.

Toast

The Toast component covers the original events and its specific instance methods as well as options. The component also provides user interaction functionality, in the sense that if a certain toast is configured to autohide, user focus or mouse over the toast will extend the time it takes for it to autohide.

For design customization and accessibility guidelines please refer back to the original plugin.

Toast Options

Name Type Default Description
animation boolean true Option to customize the component animation. If you are using a different animation other than fade, you can specify that via the data-bs-animation="ANIMATION" attribute. This will add an additional CSS class to the tooltip to enable a custom transition.
autohide boolean true Option to set a hide your toast notification automatically after being shown to the used for a certain amount of time set below. Can be set via both JavaScript and the data-bs-autohide="true" attribute.
delay number 5000 A short delay before hiding the tooltip. Can be set via JavaScript or the data-bs-delay="DELAY" attribute.

Toast Methods

The Toast component exposes two public methods as well as a static method to be used via JavaScript:

instance.show()

The method shows an initialized toast.

instance.hide()

The method hides an initialized toast, but doesn't remove the toast from the DOM.

instance.dispose()

Removes the component from target element without calling any of the above methods. Also the toast is not removed from the DOM.

instance.isShown getter

Checks if the toast is visible to the user and returns boolean.

Toast.getInstance()

A static method that allows you to access a Toast instance associated to a DOM element.

Toast Events

The event.target for the component's original events is the one with the class="toast" attribute, which is also the parent of the initialization target, usually the element having the data-bs-toggle="toast" attribute.

Event Type Description
show.bs.toast This event is fired immediately when the .show() instance method has been called.
This event can be default prevented.
shown.bs.toast This event is fired when the toast has finished being shown to the user.
hide.bs.toast This event is fired immediately when the .close() instance method has been called.
This event can be default prevented.
hidden.bs.toast This event is fired when the toast has finished being hidden from the user.

Toast DATA API

The component will initialize all elements with proper markup and the specific DATA API attributes found in the DOM. Similar to Modal or Offcanvas components, Toast can also work with trigger elements as shown in the sample markup below:

<!-- provide a trigger button -->
<button class="btn btn-primary" data-bs-toggle="toast" data-bs-target="#tastyToast" aria-controls="tastyToast">
  Button with data-bs-target
</button>
  
<!-- or an anchor link -->
<a class="btn btn-primary" data-bs-toggle="toast" href="#tastyToast" role="button" aria-controls="tastyToast">
  Link with href
</a>

<!-- and the toast itself -->
<div id="tastyToast" class="toast" role="alert" aria-live="assertive" aria-atomic="true">
  <div class="toast-header">
    <img src="..." class="rounded mr-2" alt="...">
    <strong class="mr-auto">Bootstrap</strong>
    <small>11 mins ago</small>
    <button id="myTastyToast" type="button" class="ml-2 mb-1 btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
  </div>
  <div class="toast-body">
    Hello, world! This is a toast message.
  </div>
</div>

Note that the data-bs-dismiss="toast" attribute is required for the button which dismisses the toast as well as the data-bs-toggle="toast" and data-bs-target="#toastID" attributes are required for the trigger elements.

Toast JavaScript API

After inserting a new toast notification into the page, you can initialize it via JavaScript. Considering the above markup, you can do the following:

// initialize
var myTastyToast = new BSN.Toast('#tastyToast');

Also attach listeners to the original events:

// show.bs.toast
tastyToast.addEventListener('show.bs.toast', function(event){
  // do something cool
  // this event can be default prevented
  // event.target is <div class="toast">
}, false);

// shown.bs.toast
tastyToast.addEventListener('shown.bs.toast', function(event){
  // do something cool
  // event.target is <div class="toast">
}, false);

// hide.bs.toast
tastyToast.addEventListener('hide.bs.toast', function(event){
  // do something cool
  // this event can be default prevented
  // event.target is <div class="toast">
}, false);

// hidden.bs.toast
tastyToast.addEventListener('hidden.bs.toast', function(event){
  // do something cool
  // event.target is <div class="toast">
}, false);

Like all components of the library you can access the initialization object even if it was done via the DATA API:

// find an element initialized via DATA API
var myToastButton = document.getElementById('myToastButton');

// reference the initialization object
var myToastInit = BSN.Toast.getInstance(myToastButton);

// call the public methods
myToastInit.show();
myToastInit.hide();
// or remove functionality
myToastInit.dispose();

Toast Example

Anchor Trigger Toast

Tooltip

Unlike the original plugin, our Tooltip component will initialize right away all elements with the data-bs-toggle="tooltip" attribute. Additionally, the component can do automatic placement without any options required or third party dependency and covers essential options, methods and original events.

Our implementation can automatically reposition your tooltips when needed thanks to our new PositionObserver that will trigger the update instead of the previously implemented resize and scroll event listeners.

Tooltip Options

The component covers most important options including a template option, and excluding some of the options featured in the original jQuery plugin such as a selector option for auto-initialization, or a trigger option.

Name Type Default Description
animation boolean true Option to enable/disable the tooltip animation. If you disable the animation, you can do that via the data-bs-animation="false" attribute. When enabled, this option will add an additional CSS class 'fade' to the tooltip to enable the transition.
customClass string true Option to customize the tooltip by adding a custom CSS class. You can set this option via the data-bs-custom-class="my-class" attribute.
delay number 200 A short delay before hiding the tooltip. Can be set via JavaScript or the data-bs-delay="DELAY" attribute.
placement string top Option to set a specific placement to top, bottom, left or right, relative to it's target. Can be set via both JavaScript and the data-bs-placement="POSITION" attribute.
sanitizeFn function null Option to set a function that will sanitize the title and content and the template of the tooltip. Our library doesn't include any sanitization function, you are free to use whatever solution suits your need.
This option is JavaScript API only.
template string
HTMLElement
(see description)
Allows you to set a custom template for your tooltips and overrides the default one. You can also specify a DOM node to serve as your template. The following markup is the default template for tooltips:
'<div class="tooltip" role="tooltip">
  <div class="tooltip-arrow"></div>
  <div class="tooltip-inner"></div>
</div>'
The title="" or data-bs-title="" attribute will fill in for the .tooltip-inner element.
This option allows you to set an HTMLElement to be cloned and used as the template for your Tooltip.
This option is JavaScript API only.
title string
HTMLElement
null Allows you to set a custom title to be used for your tooltip; when used via JavaScript API, it will override both the title="" and data-bs-title="" attributes.
This option allows you to set an HTMLElement to be cloned and used as the title filler for your Tooltip.
trigger string hover focus Option to change the component's trigger event: manual, hover, focus, click or any combination separated via space, except that manual cannot be combined.
* manual - makes the tooltip get shown/hidden only via the .show(), .hide() or .toggle() methods, programmed by the developer with own scripting;
* click - will toggle the tooltip visibility when click event is triggered by the user, however when the above option dismissible is true, the user can only dismiss the tooltip by clicking the <button class="btn-close"> element.
* hover - will attach mouseenter and mouseleave event listeners to show / hide the tooltip with a similar interaction when dismissible option is true;
* focus - will attach focusin and focusout event listeners to show / hide the tooltip, also taking into account the dismissible option; in some cases you may want to open a tooltip only on focus for form elements or click for other HTMLElement items.
You can set this option value via JavaScript or the data-bs-trigger="EVENT(S)" attribute.

Now since Popover extends the Tooltip component, the container option is now deprecated starting with BSN v5. When your tooltip title is an HTML markup string, remember to sanitize the content.

Tooltip Methods

For full control the Tooltip component exposes a couple of public methods as well as a static method to be used via JavaScript:

instance.show()

The method shows an initialized tooltip. When the method is executed, it will always create a new tooltip and append it into your desired container.

instance.hide()

The method hides an initialized tooltip and remove it from it's container and also from the memory, as if you would automatically destroy it.

instance.toggle()

The method shows the tooltip if hidden and hides it otherwise, using the above two methods.

instance.enable()

Starts showing the tooltip again to the user by re-adding event listeners associated to the target. Tooltips are enabled by default.

instance.disable()

Stops showing the tooltip to the user by removing event listeners associated to the target.

instance.toggleEnabled()

Toggles the enabled state by calling one of the two methods above.

instance.update()

Updates the position of the tooltip.

instance.handleTouch()

The event listener for touch enabled devices.

instance.dispose()

Removes the component from the target element.

Tooltip.getInstance()

A static method that allows you to access a Tooltip instance associated to a DOM element.

Tooltip Events

The component's original events are same as with the original jQuery Plugin, except inserted.bs.tooltip, the way the component works makes that this event is not needed, as it would fire on every instance of the .show() call.

The event.target of the original events is the target element of component, likelly your element with the data-bs-toggle="tooltip" attribute.

Event Type Description
show.bs.tooltip This event fires immediately when the show instance method is called.
This event can be default prevented.
shown.bs.tooltip This event is fired when the tooltip has been made visible to the user.
hide.bs.tooltip This event is fired immediately when the hide instance method has been called.
This event can be default prevented.
hidden.bs.tooltip This event is fired when the tooltip has finished being hidden from the user.
updated.bs.tooltip This event is fired after the tooltip has updated it's position.

Tooltip DATA API

As mentioned before the component will initialize any element found to have the data-bs-toggle="tooltip" attribute and a title or a data-bs-title attribute for SVG elements.

<!-- any regular link with data-bs-toggle="tooltip" -->
<a href="https://google.com" title="Google" data-bs-toggle="tooltip">Google</a>

<!-- any SVG shape with data-bs-toggle="tooltip" -->
<svg viewBox="0 0 80 34" width="80" height="34" xmlns="http://www.w3.org/2000/svg">
  <rect data-bs-toggle="tooltip" data-bs-placement="top" data-bs-delay="150" data-bs-title="Demo Title for SVG" rx="5"></rect>
</svg>

Tooltip JavaScript API

When you insert new items in the page and want them to initialize the component or you want to have full control over your tooltips, the JavaScript way is the best one. You can also initialize for elements not having the specific DATA API, but at least have a title="Not null title" attribute. You can do the following:

// find all elements with title attribute
var elementsTooltip = document.querySelectorAll('[title]');

// attach a tooltip for each
Array.from(elementsTooltip).forEach(
  tip => new BSN.Tooltip( tip, {
    placement: 'top', // string
    animation: true, // boolean
    customClass: 'my-rocket-tooltips', // string
    sanitizeFn: function(dirty){  // use sanitizer of your choice here
      return DOMPurify.sanitize(dirty);
    }
    delay: 150, // integer
  })
)

In addition, similar to any other component of this library, you can access the initialization and the public methods even for elements initialized via DATA API.

// find an element initialized with Tooltip
var myLinkWithTooltip = document.getElementById('myLinkWithTooltip');

// reference the initialization object
var myTooltipInit = BSN.Tooltip.getInstance(myLinkWithTooltip);

Considering the above element, let's go ahead and put the component's events to use:

// show.bs.tooltip
myLinkWithTooltip.addEventListener('show.bs.tooltip', function(event){
  // do some cool stuff when .show() method is called
  // event.target is myLinkWithTooltip
}, false);

// shown.bs.tooltip
myLinkWithTooltip.addEventListener('shown.bs.tooltip', function(event){
  // do some cool stuff when .show() method completed
  // event.target is myLinkWithTooltip
}, false);

// hide.bs.tooltip
myLinkWithTooltip.addEventListener('hide.bs.tooltip', function(event){
  // do some cool stuff when .hide() method is called
  // event.target is myLinkWithTooltip
}, false);

// hidden.bs.tooltip
myLinkWithTooltip.addEventListener('hidden.bs.tooltip', function(event){
  // do some cool stuff when .hide() method completed
  // event.target is myLinkWithTooltip
}, false);

Just because you can, you can re-initialize any element on the fly, to change options and / or content, or to just call the .show() method.

// re-initialize Tooltip and call .show()
new BSN.Tooltip('#selector',options).show();

Tooltip Examples

Now let's test all the other placement positions, we start with inline links having the bottom placement, then left, and right. Let's put it to the test! Some heavy testing on the automatic repositioning with very very long tooltips.

SVG Demo Tooltip for IMG

This is an a <div class="position-relative"> parent element to hold two position-absolute elements with Tooltip.

SVG Demo Tooltip for IMG

BaseComponent

Info

Following the development of the original library, we implemented the same solution to remove most repetitive actions common to all components; the BaseComponent provides basic functionality generally focused around determining the specific HTMLElement target or setting instance options.

It also throws an error when no target HTMLElement is found and removes existing instances which is important to prevent memory overflow or breaking the component functionality.

Base Properties And Methods

The BaseComponent component exposes some getters for all components to use:

instance.name

Returns the name of the component used to initialize the current instance.

instance.defaults

Returns the component default options values.

instance.version

Returns the library version.

instance.dispose()

Removes the component from target element. Components generally extend this method with additional specific functionality.