Show Only One Popover with Dynamic Popovers
by bizamajig
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/js/bootstrap.bundle.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.min.css">
<div class="example">
<p><label id="use-selector-label" class="checkbox"><input id="use-selector" type="checkbox" checked/> <span data-title="you must re-run this jsFiddle to change the selector option once you've started the demo">use selector option</span></label></p>
<pre id="with-selector-code">$('body').popover({
selector: '[rel=popover]'
});</pre>
<pre id="without-selector-code">$('[rel="popover"]').popover();</pre>
<p><a id="add-button" class="btn btn-sm btn-success">add new popover</a></p>
<div class="buttons">
<hr />
<p><a class="btn btn-lg btn-danger" rel="popover" data-title="Static" data-content="This button was specified in the initial HTML document" data-placement="top">click for popover</a></p>
</div>
</div>
CSS
.example
{
margin: 8px 80px;
}
.buttons, pre
{
display: none;
}
.popover.fade {
z-index:-1;
}
.popover.fade.in {
z-index:2;
}
JavaScript
function usingSelectorOption() {
return $('#use-selector').is(':checked');
}
function updateCodeView() {
$('#with-selector-code').toggle(usingSelectorOption());
$('#without-selector-code').toggle(!usingSelectorOption());
}
$(function() {
// update code view when checkbox is toggled
updateCodeView();
$('#use-selector').click(function() {
updateCodeView();
});
var startedDemo = false;
$('#add-button').click(function() {
// One-time initialization
if (!startedDemo) {
if (usingSelectorOption()) {
$('body').popover({
selector: '[rel=popover]',
trigger: "click"
}).on("show.bs.popover", function(e){
// hide all other popovers
$("[rel=popover]").not(e.target).popover("destroy");
$(".popover").remove();
}).on("hide.bs.popover", function(){
console.log("i'm hiding");
});
} else {
$('[rel="popover"]').popover();
}
startedDemo = true;
}
// disable selector checkbox, put a tooltip on it, and show the buttons panel
$('#use-selector').attr('disabled', 'disabled');
$('#use-selector-label span').tooltip();
$('.buttons').show();
// add a new button that triggers (or doesn't) a popover, with the appropriate message
var does = usingSelectorOption() ? 'DOES' : 'does NOT';
$('<p><a class="btn btn-lg btn-danger" rel="popover" data-title="Dynamic" data-content="This button was added dynamically by JavaScript" data-placement="top">notice that this ' + does + ' trigger a popup</a></p>').appendTo('.buttons');
});
});