Bootstrap Popovers

You will discover how to make popovers with Bootstrap in this article.


Creating Popovers with Bootstrap

A popover is a small content overlay used to display additional information related to an element when clicked by the user, similar to those seen on the iPad.

Step 1: Adding the Popover Markup

To create a popover, you need to include the data-bs-toggle=popover attribute within the desired element. The popover's title and content, which will be displayed upon activation, can be specified using the title and data-bs-content attributes, 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 other elements such as links, icons, and so on.

Note: It's important to note that, similar to tooltips, popovers' data-apis are opt-in for performance reasons. This means you must initialize popovers yourself to use them. Additionally, popovers with zero-length title and content values will not be displayed, and triggering popovers on hidden elements will not work.

Step 2: Enabling the Popovers

Popovers can be triggered using JavaScript by calling the popover() Bootstrap method with the appropriate id , class , or CSS selector of the target element in your JavaScript code.

You have the option to initialize popovers individually or all at once. The following example code will initialize all popovers on the page by selecting them based on their data-bs-toggle attribute.

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

Setting the Directions of Popovers

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

Positioning of Popovers via Data Attributes

The following example demonstrates how to set the direction of popovers using data attributes.

<div class="bs-example">
    <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>
</div>

Positioning of Popovers via JavaScript

In the following example, you will learn how to set the popover direction using JavaScript.

<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 do not hide until you click the trigger element again. However, you can use the focus trigger to hide the popovers when the user clicks elsewhere.

<a href="#" class="btn btn-primary" data-bs-toggle="popover" tabindex="0" data-bs-trigger="focus" title="Popover title" data-bs-content="Default popover">Dismissible popover</a>

Note: To ensure this feature works properly across browsers, it's essential to use the <a> tag instead of the <button> tag and include a tabindex attribute.


Bootstrap Popover Options

There are specific options that can be utilized with the popover() Bootstrap method to customize the behavior of the popover plugin.

  • Animation: Type: boolean, Default: true

    Apply a fade transition to the popover when set to true using CSS.

  • Container: Type: string | element | false, Default: false

    Append the popover to a specific element. To avoid rendering issues in more complex components like input groups and button groups, specify container: 'body'.

  • Content: Type: string | element | function, Default: ''

    If the data-bs-content attribute is not present, you can set a default content value.

  • Delay: Type: number | object, Default: 0

    Set a delay for showing and hiding the popover using a number or an object. If a number is provided, the delay is applied to both show and hide actions. The object structure for delay is { "show": 500, "hide": 100 }.

  • HTML: Type: boolean, Default: false

    The html option allows you to insert HTML content into the popover. If set to false, the content will be inserted as plain text using the innerText property. This can be useful to prevent cross-site scripting (XSS) attacks.

  • Placement: Type: string | function, Default: 'right'

    The placement option determines the position of the popover and can be set to 'auto', 'top', 'bottom', 'left', or 'right'. When auto is specified, the popover will dynamically adjust its position.

  • Selector: Type: string | false, Default: false

    By providing a selector, you can attach popovers to specific targets. This is commonly used when adding popovers to dynamically generated DOM elements.

  • Template: Type: string, Default: html code

    The template option allows you to define the base HTML structure of the popover. The title will be inserted into the .popover-header element, the content into the .popover-body element, and the arrow into the .popover-arrow element. The outermost element should have the class .popover.

  • Title: Type: string | element | function, Default: ''

    If the title attribute is not present, you can set a default title value.

  • Trigger: Type: string, Default: click

    The trigger option specifies how the popover is triggered and can be set to 'click', 'hover', 'focus', or 'manual'. Multiple triggers can be passed as a space-separated string. The manual value indicates that the popover will be programmatically triggered using methods like .show(), .hide(), and .toggle(), and cannot be combined with other triggers.

  • Sanitize: Type: boolean, Default: true

    The sanitize option enables or disables content sanitization. When activated, the 'template', 'content', and 'title' options will be sanitized.

  • Offset: Type: array | string | function, Default: [0, 8]

    The offset determines the positioning of the popover in relation to its target. You can provide an offset value as an array, a string with comma-separated values, or even set it using data attributes such as data-bs-offset="10,20".

You have the flexibility to configure these options either through data attributes or using JavaScript. To set popover options via data attributes, simply append the option name to data-bs- along with the desired value, like data-bs-animation=false, data-bs-placement=top, etc.

When passing options via data attributes, it's essential to change the case type of the option name from camelCase to kebab-case. For instance, instead of using data-bs-customClass=my-class, use data-bs-custom-class=my-class.

However, the preferred method for setting these options is using JavaScript, as it avoids redundancy. Refer to the passing options section below to understand how to set popover options via JavaScript.


Bootstrap Popover Methods

These are the standard Bootstrap popover methods:

Passing options

Additionally, you can pass options to popovers using the options object.

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

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

The example below illustrates how to position HTML content within a popover:

<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 straightforward illustration showcasing the process of inserting HTML code within a <strong>Bootstrap popover</strong>.</p>',
                            html: true
                        });
                    });
</script>

Another example demonstrates how to control the timing of showing and hiding the popover using the popover's delay option dynamically via JavaScript.

<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>

Moreover, you can create a custom template for Bootstrap popovers instead of using the default one, as shown in this example:

<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>

If you want to insert the dynamically generated HTML code of the popover at the end of a specific element (e.g., #wrapper) instead of the default <body> element, you can do so with JavaScript.

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

Note: Remember that overriding the popover's default container option value may not produce a visible difference on the page. To observe the actual result, you need to inspect the DOM using developer tools or DOM Inspector.

Furthermore, there are other options available for customizing popovers, which are detailed in the other methods of the Bootstrap popover plugin.

show

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.

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

hide

This function conceals the popover of an element, providing a manual means of triggering it.

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

toggle

This function toggles the visibility of an element's popover, allowing for manual activation.

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

enable

This function enables the display of an element's popover, as popovers are enabled by default.

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

disable

This function disables the visibility of an element's popover, requiring re-enabling to make it appear again.

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

toggleEnabled

This method switches the visibility of an element's popover, allowing it to be shown or hidden.

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

update

This method adjusts the placement of an element's popover to update its position.

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

Bootstrap Popover Events

The popover class in Bootstrap provides a few events that can be utilized to integrate with popover functionality.

  • show.bs.popover: This event triggers immediately when the show instance method is invoked.
  • shown.bs.popover: This event is activated when the popover becomes visible to the user. It waits until the CSS transition process is complete before triggering.
  • hide.bs.popover: This event occurs immediately after the hide instance method is called.
  • hidden.bs.popover: This event is triggered when the popover has finished hiding from the user. It waits until the CSS transition process is complete before triggering.
  • inserted.bs.popover: This event takes place after the show.bs.popover event when the popover template has been added to the DOM.

Finally, if you want to display an alert message to the user when the fade-out transition of the popover is fully completed, you can use the following example to achieve that.

<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>

FAQ

What is a Bootstrap Popover?

A Bootstrap Popover is a UI component that provides additional information or options when a user interacts with an element, typically by hovering over it or clicking on it. It's a small overlay that appears on top of the content and can contain text, images, links, or any other HTML content.

How do you activate a Bootstrap Popover?

To activate a Bootstrap Popover, you need to include the data-toggle="popover" attribute on the element you want to trigger the popover. You also need to specify the content you want to display in the popover using the data-content attribute. For example:

<button type="button" class="btn btn-primary" data-toggle="popover" data-content="This is a popover content.">Click Me</button>

How can you customize the placement of a Popover?

Bootstrap Popovers can be placed in different positions relative to the triggering element. You can customize the placement using the data-placement attribute. Possible values include top, bottom, left, and right. For instance:

<button type="button" class="btn btn-primary" data-toggle="popover" data-placement="top" data-content="Top popover content.">Hover Me</button>

Can you trigger a Popover on hover instead of click?

Yes, you can trigger a Bootstrap Popover on hover by using the data-trigger attribute with the value "hover". This way, the popover will appear when the user hovers over the element. Example:

<button type="button" class="btn btn-primary" data-toggle="popover" data-trigger="hover" data-content="Hover-triggered popover.">Hover Me</button>

How do you initialize Popovers using JavaScript?

You can also initialize Bootstrap Popovers programmatically using JavaScript. First, make sure you have included the Bootstrap JavaScript library. Then, you can use the popover() method to initialize popovers. For example:

$(document).ready(function () {
    $('[data-toggle="popover"]').popover();
});

Can Popovers contain HTML content?

Yes, Bootstrap Popovers can contain HTML content. By default, the content specified in the data-content attribute is treated as plain text. However, if you want to include HTML content, you can use the data-html attribute and set it to true. Example:

<button type="button" class="btn btn-primary" data-toggle="popover" data-html="true" data-content="<strong>HTML</strong> content in popover.">Click Me</button>

How can you add a title to a Bootstrap Popover?

You can add a title to a Bootstrap Popover by using the data-original-title attribute. This attribute specifies the title that will be displayed at the top of the popover. Here's an example:

<button type="button" class="btn btn-primary" data-toggle="popover" data-content="Content goes here" data-original-title="Popover Title">Click Me</button>

Can you manually show or hide a Popover using JavaScript?

Yes, you can manually control the visibility of a Bootstrap Popover using JavaScript. To show a popover, use the .popover('show') method, and to hide it, use the .popover('hide') method. Here's how you can do it:

$(document).ready(function () {
    $('[data-toggle="popover"]').popover();

    // Manually show popover
    $('#showPopoverButton').click(function () {
        $('[data-toggle="popover"]').popover('show');
    });

    // Manually hide popover
    $('#hidePopoverButton').click(function () {
        $('[data-toggle="popover"]').popover('hide');
    });
});

How can you add options to a Popover using data attributes?

You can add additional options to a Bootstrap Popover using data attributes. For example, you can control whether the popover is dismissible by clicking outside of it by using the data-trigger attribute. Additionally, you can specify a delay before the popover appears or disappears using data-delay. Here's an example:

<button type="button" class="btn btn-primary" data-toggle="popover" data-content="Popover content" data-trigger="click" data-delay="500">Click Me</button>

Are Bootstrap Popovers responsive?

Yes, Bootstrap Popovers are designed to be responsive by default. They will adjust their placement based on available space in the viewport. If a popover's placement would cause it to go outside the visible area, Bootstrap will automatically reposition it to ensure it remains within view.

Can you use custom HTML templates for Popovers?

Yes, you can use custom HTML templates for the content of Bootstrap Popovers. This allows you to create more complex and styled popovers. To do this, you need to create an element with the desired content, and then use the data-content attribute to reference the element's ID. For instance:

<button type="button" class="btn btn-primary" data-toggle="popover" data-html="true" data-content="#customPopoverContent">Click Me</button>

<div id="customPopoverContent" class="d-none">
    <h3>Custom Popover</h3>
    <p>This is a custom HTML popover content.</p>
</div>

In this example, the data-content attribute references the ID of the hidden div containing the custom content.

Can you customize the styling of the popover arrow?

Yes, you can customize the styling of the popover arrow using CSS. Bootstrap provides classes like .arrow and .arrow::before that you can target to apply your custom styles to the arrow element. For example, you can change the color or size of the arrow.

/* Customize popover arrow color */
.popover .arrow {
    border-bottom-color: red;
}

/* Customize popover arrow size */
.popover .arrow::before {
    border-width: 15px;
}

How can you prevent a Popover from closing when clicking inside it?

By default, Bootstrap Popovers close when you click anywhere outside of the popover, including inside the popover itself. If you want to prevent the popover from closing when clicking inside, you can use the data-container attribute to specify a container element. This way, clicking inside the popover won't trigger its closure.

<button type="button" class="btn btn-primary" data-toggle="popover" data-content="Clicks inside won't close me!" data-container="body">Click Me</button>

Can you have multiple Popovers on the same page?

Yes, you can have multiple Bootstrap Popovers on the same page. Each popover should have its own unique triggering element with the data-toggle="popover" attribute. You can customize the content, placement, and other attributes for each popover individually.

<button type="button" class="btn btn-primary" data-toggle="popover" data-content="Popover 1 content">Popover 1</button>
<button type="button" class="btn btn-secondary" data-toggle="popover" data-content="Popover 2 content">Popover 2</button>

Are there any events associated with Popovers?

Yes, Bootstrap provides several events that you can use to customize the behavior of Popovers. Some useful events include show.bs.popover (before a popover is shown), shown.bs.popover (after a popover is shown), hide.bs.popover (before a popover is hidden), and hidden.bs.popover (after a popover is hidden). You can attach event listeners to these events using JavaScript.

How can you destroy a Popover and remove its functionality?

If you need to remove the popover functionality from an element, you can use the .popover('dispose') method. This method removes the popover-related data and events from the element. For example:

$(document).ready(function () {
    // Initialize popover
    $('[data-toggle="popover"]').popover();

    // Remove popover functionality
    $('#removePopoverButton').click(function () {
        $('[data-toggle="popover"]').popover('dispose');
    });
});

Can you adjust the Popover's arrow position?

While Bootstrap Popovers automatically position their arrow to point at the center of the triggering element, you can fine-tune the arrow's position using CSS transformations like translateX and translateY to adjust its placement relative to the default position.

.popover .arrow {
    transform: translateX(-50%) translateY(5px);
}

Can you make the Popover dismissible with a close button?

By default, Bootstrap Popovers don't have a built-in close button. However, you can manually add a close button within the popover content and use JavaScript to close the popover when the button is clicked.

<button type="button" class="btn btn-primary" data-toggle="popover" data-content="<button class='close-popover btn btn-link'>&amp;times;</button> Popover content">Click Me</button>

<script>
    $(document).ready(function () {
        $(document).on('click', '.close-popover', function () {
            $(this).closest('.popover').popover('hide');
        });
    });
</script>

How can you customize the appearance of the popover's arrow?

You can customize the appearance of the popover's arrow using CSS. You can target the .arrow class within the popover to apply styles like background color, border color, and size to the arrow element. For example:

.popover .arrow {
    background-color: blue;
    border-color: blue;
    width: 20px;
    height: 10px;
}

How can you set a maximum width for a Popover?

To set a maximum width for a Bootstrap Popover, you can use CSS to target the .popover-content class within the popover and apply the desired max-width property.

.popover-content {
    max-width: 300px;
}

Can you position the Popover without an arrow?

The default behavior of Bootstrap Popovers is to display an arrow pointing to the triggering element. If you prefer not to show the arrow, you might need to use custom CSS to hide or style the arrow. You can target the .arrow class within the popover to manipulate its appearance.

.popover .arrow {
    display: none;
}

Conclusion

Bootstrap Popover emerges as a versatile and user-friendly tool, offering a dynamic way to present interactive and contextual information within web applications. The framework's commitment to a seamless user experience is evident in its array of features, including Interactive Information Popovers, Dynamic Tooltip Popovers, and Contextual Popup Messages, providing users with informative and engaging content.

The User-Friendly Popover Components and Customizable Popover Design highlight the adaptability of popovers, allowing developers to tailor their appearance to match specific design requirements. The concept of a Tooltip Overlay enhances the overall user interface, offering triggered information popups that respond to user interactions.

The responsiveness of popovers extends to Hover-Activated Popovers and Responsive Popup Messages, ensuring a consistent and engaging presentation across different devices. Developers benefit from a range of Popover Styling Options and the ability to incorporate Dynamic Content Popovers, allowing for a diverse and visually appealing popover experience.

In addition to its rich feature set, Bootstrap Popover provides precise control over positioning and directional orientation, as evidenced in Popover Positioning, Configure Popover Directions, and Placement Settings for Popovers. The dynamic nature of popovers is further enhanced by the ability to Hide and Show Popovers Dynamically, providing developers with flexibility in controlling popover visibility.

The Popover Positioning Flexibility and Customizable Tooltip Styling further contribute to the adaptability of popovers, accommodating various design preferences. Moreover, the concept of Dynamic Styling for Popovers allows developers to apply real-time changes to enhance the overall aesthetics and user interaction.