Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide Bootstrap Popover if parent element is removed

How do you hide a bootstrap popover if the parent element, that triggered this popover, is removed from the dom?

If a user clicks a button on my page, some content will be loaded into a div via ajax. On the next click on a different button, another ajax call will replace the content in this same div.

The content loaded into this div contains elements that act as Bootstrap Popover triggers, like this one:

<a class="infolink" data-toggle="popover" data-title="some title" data-placement="bottom" data-trigger="hover click" ></a>

The popovers get initialized after every successful ajax call:

$(document).ajaxSuccess(function(){
           var init = function() {
                $('[data-toggle="popover"]').each(function(index) {
                    initPopover(this); //This is where the popover gets initialized
                });
            }
            window.setTimeout(init,100); // set timeout to prevent function from being executed before content is replaced
       });

The problem after a ajax call is, if a popup was visible, it stays visible even after the parent element has been removed. This is not an uncommon issue with popovers or dialogs according to google results, but the solutions I've come across so far did not seem very clean to me.

Two solutions, just to name some:
Hide every popover once an ajax finishes with success. This is not an option, because the content of my popovers is loaded dynamically via ajax once they get opened.

Have an array store all trigger elements. Once a Ajax success event occurs, loop through that array and check if that element is still there.

//Pseudocode
var popoverTriggers = [];
$('[data-toggle="popover"]').each(function(index) {
    popoverTriggers.push(this);
}

Doesn't seem very clean to me either.

Does anyone know of a better way to do this?

like image 651
Jbartmann Avatar asked Mar 02 '17 14:03

Jbartmann


People also ask

How do you hide a popover?

To hide the displayed popover, use the popover(“hide”) method.

How do I destroy bootstrap popover?

Use the popver(“detroy”) to destroy the popover.

What is data toggle popover?

The Popover plugin is similar to tooltips; it is a pop-up box that appears when the user clicks on an element. The difference is that the popover can contain much more content. Click To Toggle Popover Click To Toggle Popover.


1 Answers

I added a

$('.popover').remove();

To the event that should trigger the removal of the popover. This worked great for me.

like image 139
sparkyShorts Avatar answered Nov 04 '22 01:11

sparkyShorts