Reputation: 1539
When using bootstrap popovers you have to initialize them in your javascript code like this $('#element').popover();
. Usually you would use a $(document).ready();
function for that. But what if the element the popover gets bound to is loaded by ajax itself?
Being not fully confident with javascript, the current issue I'm facing is with having a page that's loading a huge part of its content via multiple ajax calls. One of these elements are:
<span class="infolink" style="vertical-align:bottom;" data-title="some title" data-placement="bottom" data-delay="500" data-content="some content">
Trigger Popover
</span>
One solution that came to my mind, after each ajax call cycle through all elements and initialize the popover (e.g.: $('.infolink').each(function(i,e){e.popover();});
). I don't want to this, since this would hurt performance, given the number of ajax calls and the size of the page. Is there any other way?
Another idea was having a function (e.g. function initializePopover(element){...}
) and calling it after the element has been loaded <span class="infolink" [...] onload="initializePopover(this)"></span>
. But this did not work either.
Is there a best-practice to how to initialize popovers where the trigger-element itself is to be loaded by ajax?
Upvotes: 1
Views: 4660
Reputation: 1058
You have two solutions in : https://stackoverflow.com/a/11947156/2660794 you can choose the one that suites you..
Upvotes: 1
Reputation: 6902
Use jQuery's event delegation mechanism to capture elements which are loaded in an asynchronous manner:
let's say the following html is loaded from an AJAX call:
<span class="infolink" style="vertical-align:bottom;" data-title="some title" data-placement="bottom" data-delay="500" data-content="some content">
Trigger Popover
</span>
your binding will look like this:
$(document).on("click", ".infolink", function(e) {
$(e.target).popover();
});
This is basically an alias to the following logic:
document
element (which is basically everywhere)in that way, even if the element appeared later on - you'll still be able to bind event callbacks to it.
Upvotes: 5
Reputation: 962
I think the best way to go is once your ajax call is complete add a
$('.infolink').popover();
You don't need a loop for that.
Upvotes: 0