Bootstrap Popovers

Creating Popovers with Bootstrap

Popover is a small overlay of content that is used to display secondary information of any element when it is clicked by a user, like those on the iPad.

Step 1: Adding the Popover Markup

To create a popover, you need to add the data-bs-toggle="popover" attribute to an element. Whereas, popover’s title and its content that would display upon trigger or activation can be specified using the title and data-bs-content attribute respectively.

Here is the standard markup for adding a popover to a button.

<button type=”button” data-bs-toggle=”popover” title=”Popover title” data-bs-content=”Here’s some amazing content.”>Click to toggle popover</button>

Similarly, you can add popovers to the other elements such as links, icons, etc.

Note: For performance reasons the popovers data-apis are opt in like tooltips, means to use popovers you must initialize them yourself. Also, popovers with zero-length title and content values are never displayed, as well as triggering popovers on hidden elements will not work.

Step 2: Enabling the Popovers

Popovers can be triggered via JavaScript — just call the popover() Bootstrap method with the idclass or any CSS selector of the required element in your JavaScript code.

You can either initialize popovers individually or all in one go. The following example code will initialize all popovers on the page by selecting them by their data-bs-toggle attribute.

Example

jQuery JavaScript

Try this code »

<script>
$(document).ready(function(){
    $('[data-bs-toggle="popover"]').popover();  
});
</script>

— The output of the above example will look something like this:

Bootstrap Popover

Setting the Directions of Popovers

You can set popovers to appear on top, right, bottom and left sides of an element.

Positioning of Popovers via Data Attributes

The following example will show you how to set the direction of popovers via data attributes.

Example

Try this code »

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

Positioning of Popovers via JavaScript

The following example will show you how to set the direction of popovers via JavaScript.

Example

jQuery JavaScript

Try this code »

<script>
$(document).ready(function(){
    $("#popTop").popover({placement : "top"});
    $("#popRight").popover({placement : "right"});
    $("#popBottom").popover({placement : "bottom"});
    $("#popLeft").popover({ placement : "left"});
});
</script>

Hiding the Popovers on Next Click

By default popovers are not hiding until you click the trigger element once again. You can use the focus trigger to hide the popovers when the user makes the next click.

Example

Try this code »

<a href="#" class="btn btn-primary" tabindex="0" data-bs-toggle="popover" data-bs-trigger="focus" title="Popover title" data-bs-content="Here's some amazing content.">Dismissible popover</a>

Note: To make this feature work properly across the browsers, you must use the <a> tag, not the <button> tag, and you also must include a tabindex attribute.


Options

There are certain options which may be passed to popover() Bootstrap method to customize the functionality of the popover plugin.

NameTypeDefault ValueDescription
animationbooleantrueApply a CSS fade transition to the popover.
containerstring | element | falsefalseAppends the popover to a specific element.Specify container: 'body' to avoid rendering problems in more complex components (like input groups, button groups, etc.)
contentstring | element | functionSets default content value if data-bs-content attribute isn’t present.
delaynumber | object0Time to delay in showing and hiding the popover (ms) — does not apply to manual trigger type.If a number is supplied, delay is applied to both hide/showObject structure is: delay: { "show": 500, "hide": 100 }
htmlbooleanfalseInsert HTML into the popover.If falseinnerText property will be used to insert content into the DOM.Use simple text if you’re worried about XSS attacks.
placementstring | function‘right’Sets the position of the popover — auto | top | bottom | left | right.When auto value is specified, it will dynamically reorient the popover.
selectorstring | falsefalseIf a selector is provided, popover objects will be attached to the specified targets.This is normally used to apply popovers to dynamically added DOM elements.
templatestring'<div class="popover"><div class="popover-arrow"></div><h3 class="popover-header"></h3><div class="popover-body"></div></div>'Base HTML to use when creating the popover.The popover’s title will be inserted into the .popover-header element.The popover’s content will be inserted into the .popover-body element.The .popover-arrow element will become the popover’s arrow.The outermost wrapper element should have the .popover class.
titlestring | element | functionSets the default title value if title attribute isn’t present.
triggerstring‘click’Specify how popover is triggered — click | hover | focus | manual. You can pass multiple triggers; separated with a space.The value manual indicates that the popover will be triggered programmatically via the .show().hide() and .toggle() methods; this value cannot be combined with any other trigger.
fallbackPlacementsarray[‘top’, ‘right’, ‘bottom’, ‘left’]Allows you to specify which placement Popper will use on fallback.
boundarystring | element‘clippingParents’Overflow constraint boundary of the popover (applies only to Popper’s preventOverflow modifier). It can also accept an HTMLElement reference (via JavaScript only).
customClassstring | functionAdd classes to the popover when it is shown. Please note that these classes will be added in addition to any classes specified in the template. To add multiple classes, separate them with spaces like: 'class1 class2'.You can also pass a function that should return a single string containing additional class names.
sanitizebooleantrueEnable or disable the sanitization. If activated 'template''content' and 'title' options will be sanitized.
allowListobjectDefault valueObject which contains allowed attributes and tags.
sanitizeFnnull | functionnullAllows you to specify your own sanitize function.
offsetarray | string | function[0, 8]Offset of the popover relative to its target. You can also pass a string in data attributes with comma separated values like: data-bs-offset="10,20"
popperConfignull | object | functionnullAllows you to change Bootstrap’s default Popper config, see Popper’s configuration.

You can set these options either through the use of data attributes or JavaScript. For setting the popovers options via data attributes, just append the option name to data-bs- along with the correct value, like data-bs-animation="false"data-bs-placement="top" etc.

Also, when passing the options via data attributes make sure to change the case type of the option name from camelCase to kebab-case. For example, instead of using data-bs-customClass="my-class", use data-bs-custom-class="my-class".

However, JavaScript is the preferred way of setting these options as it prevents you from repetitive work. See the passing options section below to know how to set the options for popovers via JavaScript.


Methods

These are the standard Bootstrap’s popover methods:

Passing options

You can additionally pass options to the popovers using options object.

The following example will set the title text for the popovers dynamically, if the value of the title attribute is omitted or missing from the selected elements:

Example

jQuery JavaScript

Try this code »

<script>
$(document).ready(function(){
    $("#myPopover").popover({
        title : "Default popover title"
    });
});
</script>

The following example will show you how to place the HTML content inside a popover:

Example

jQuery JavaScript

Try this code »

<script>
$(document).ready(function(){
    $("#myPopover").popover({
        title: '<h4 class="custom-title"><i class="bi-info-circle-fill"></i> Popover info</h4>',
        content: '<p>This is a <em>simple example</em> demonstrating how to insert HTML code inside <strong>Bootstrap popover</strong>.</p>',
        html: true
    }); 
});
</script>

The following example will show you how to control the timing of showing and hiding the popover using the popover’s delay option dynamically via JavaScript.

Example

jQuery JavaScript

Try this code »

<script>
$(document).ready(function(){
    // Show and hide popover with same speed
    $("#tinyPopover").popover({
        delay: 100
    });
    
    // Show and hide popover with different speed
    $("#largePopover").popover({
        delay: {show: 0, hide: 2000}
    }); 
});
</script>

The following example will show you how to create your own custom template for Bootstrap popovers instead of using the default one dynamically via JavaScript.

Example

jQuery JavaScript

Try this code »

<script>
$(document).ready(function(){
    $('[data-bs-toggle="popover"]').popover({
        template: '<div class="popover"><div class="popover-arrow"></div><h3 class="popover-header"></h3><div class="popover-body"></div><div class="popover-footer"><a class="btn btn-secondary btn-sm close">Close</a></div></div>'
    });

    // Close popover on button click
    $(document).on("click", ".popover .close" , function(){
        $(this).parents(".popover").popover("hide");
    });
});
</script>

The following example will insert the dynamically generated HTML code of the popover at the end of the #wrapper element instead of the default <body> element.

Example

jQuery JavaScript

Try this code »

<script>
$(document).ready(function(){
    // Append popover HTML to wrapper element
    $("#myPopover").popover({
        container: "#wrapper"
    }); 
});
</script>

Note: Overriding the popover’s default container option value does not produce any visible difference on page. To see the actual result you need to inspect the DOM. Press Ctrl+Shift+I (Windows / Linux) or Cmd+Opt+I (Mac) to open Developer tools or DOM Inspector.

Similarly, you can set other options for the popovers. Let’s check out the other methods of the Bootstrap popover plugin.

show

This method reveals an element’s popover. This is considered a “manual” triggering of the popover.

Example

jQuery JavaScript

Try this code »

<script>
$(document).ready(function(){
    $("#myBtn").click(function(){
        $("#myPopover").popover("show");
    }); 
});
</script>

hide

This method hides an element’s popover. This is considered a “manual” triggering of the popover.

Example

jQuery JavaScript

Try this code »

<script>
$(document).ready(function(){
    $("#myBtn").click(function(){
        $("#myPopover").popover("hide");
    }); 
});
</script>

toggle

This method toggles an element’s popover. This is considered a “manual” triggering of the popover.

Example

jQuery JavaScript

Try this code »

<script>
$(document).ready(function(){
    $("#myBtn").click(function(){
        $("#myPopover").popover("toggle");
    }); 
});
</script>

dispose

This method hides and destroys an element’s popover (i.e. removes stored data on the DOM element).

Example

jQuery JavaScript

Try this code »

<script>
$(document).ready(function(){
    $("#myBtn").click(function(){
        $("#myPopover").popover("dispose");
    }); 
});
</script>

enable

This method gives an element’s popover the ability to be shown. Popovers are enabled by default.

Example

jQuery JavaScript

Try this code »

<script>
$(document).ready(function(){
    $("#myBtn").click(function(){
        $("#myPopover").popover("enable");
    }); 
});
</script>

disable

This method removes the ability for an element’s popover to be shown. The popover will only be able to be shown if it is re-enabled.

Example

jQuery JavaScript

Try this code »

<script>
$(document).ready(function(){
    $("#myBtn").click(function(){
        $("#myPopover").popover("disable");
    }); 
});
</script>

toggleEnabled

This method toggles the ability for an element’s popover to be shown or hidden.

Example

jQuery JavaScript

Try this code »

<script>
$(document).ready(function(){
    $("#myBtn").click(function(){
        $("#myPopover").popover("toggleEnabled");
    }); 
});
</script>

update

This method updates the position of an element’s popover.

Example

jQuery JavaScript

Try this code »

<script>
$(document).ready(function(){
    $("#myBtn").click(function(){
        $("#myPopover").popover("update");
    }); 
});
</script>

getInstance

This is a static method which allows you to get the popover instance associated with a DOM element.

Example

jQuery JavaScript

Try this code »

<script>
$(document).ready(function(){
    // Trigger the popover
    $("#myPopover").popover();
    
    // Get popover instance on button click
    $("#myBtn").click(function(){      	
        var myPopover = bootstrap.Popover.getInstance($("#myPopover")[0]);
        console.log(myPopover);
        // {_element: button#myPopover.btn.btn-primary.btn-lg, _isEnabled: true, _timeout: 0, _hoverState: null, _activeTrigger: {…}, …}
    });
});
</script>

getOrCreateInstance

This is a static method which allows you to get the popover instance associated with a DOM element, or create a new one in case if the popover wasn’t initialized.

Example

jQuery JavaScript

Try this code »

<script>
$(document).ready(function(){
    // Get or create popover instance on button click
    $("#myBtn").click(function(){
        var myPopover = bootstrap.Popover.getOrCreateInstance($("#myPopover")[0]);
        console.log(myPopover);
        // {_element: button#myPopover.btn.btn-primary.btn-lg, _isEnabled: true, _timeout: 0, _hoverState: "", _activeTrigger: {…}, …}
    });
});
</script>

Events

Bootstrap’s popover class includes few events for hooking into popover functionality.

EventDescription
show.bs.popoverThis event fires immediately when the show instance method is called.
shown.bs.popoverThis event is fired when the popover has been made visible to the user. It will wait until the CSS transition process has been fully completed before getting fired.
hide.bs.popoverThis event is fired immediately when the hide instance method has been called.
hidden.bs.popoverThis event is fired when the popover has finished being hidden from the user. It will wait until the CSS transition process has been fully completed before getting fired.
inserted.bs.popoverThis event is fired after the show.bs.popover event when the popover template has been added to the DOM.

The following example will display an alert message to the user when the fade out transition of the popover has been fully completed.

Example

jQuery JavaScript

Try this code »

<script>
$(document).ready(function(){
    // Initialize popover
    $("#myPopover").popover();

    // Show alert when the popover has finished being hidden 
    $("#myPopover").on("hidden.bs.popover", function(){
        alert("Popover has been completely closed.");
    });
});
</script>

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *