Problem:
I am trying to create multiple Bootstrap popover instances with the ability to close all when on click.
Here is what I did
document.addEventListener('DOMContentLoaded', function () {
var items = [];
document.getElementById('addPopperButton', function () {
var btn = document.createElement('button');
btn.setAttribute('type', 'button');
btn.innerText = 'Toggle poppver';
var item = new bootstrap.Popover(btn, {
trigger: 'hover click',
title: 'lorem text',
content: 'lorem text'
});
items.push(item);
document.body.appendChild(btn);
});
document.getElementById('hideAllPopovers', function () {
items.forEach(item => {
item.popover('hide');
});
});
});
However this keeps giving me the following error
Uncaught TypeError: item.popover is not a function
How can I manually hide all the popover instances when the hideAllPopovers
is clicked?
Solution:
In Bootstrap 5, you can hide a popover using hide
method:
const popoverInstance = new bootstrap.Popover(triggerElement, options);
// manually hide
popoverInstance.hide()
$().popover('hide')
was used in Bootstrap v3 & 4.
In your code, item
is a popover instance, so you should replace item.popover('hide');
with item.hide();
.
document.getElementById('hideAllPopovers').addEventListener('click', () => {
items.forEach((item) => {
item.hide();
});
});
Stackblitz demo:
https://stackblitz.com/edit/stackblitz-starters-chdxor?file=src%2Findex.js
From Bootstrap 5 docs, hide
method:
Hides an element’s popover. Returns to the caller before the popover has actually been hidden (i.e. before the hidden.bs.popover event occurs). This is considered a “manual” triggering of the popover.