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?
2
Answers
In Bootstrap 5, you can hide a popover using
hide
method:$().popover('hide')
was used in Bootstrap v3 & 4.In your code,
item
is a popover instance, so you should replaceitem.popover('hide');
withitem.hide();
.Stackblitz demo:
https://stackblitz.com/edit/stackblitz-starters-chdxor?file=src%2Findex.js
From Bootstrap 5 docs,
hide
method:From the docs one way to get an instance of a popper object for an element is like
Here’s a demo: