1

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?

Jbartmann
  • 1,459
  • 4
  • 24
  • 42
  • I assume that the various ajax calls add html to the dom. You could just try to select in the added snippet instead of the whole page. – Bryan Euton Mar 01 '17 at 14:01

3 Answers3

5

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:

  1. when clicking on the document element (which is basically everywhere)
  2. check if the click bubbled from ".infolinks"
  3. if it did - dispatch the events callback

in that way, even if the element appeared later on - you'll still be able to bind event callbacks to it.

silicakes
  • 6,364
  • 3
  • 28
  • 39
1

You have two solutions in : https://stackoverflow.com/a/11947156/2660794 you can choose the one that suites you..

Community
  • 1
  • 1
Christophe Ferreboeuf
  • 1,048
  • 14
  • 26
0

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.

Stavros Angelis
  • 962
  • 5
  • 8