Twitter Bootstrap Popovers not working for Dynamically Generated Content

ryzh picture ryzh · Aug 14, 2012 · Viewed 25k times · Source

New to posting on stackoverflow here, so my apologies in advance if I messed anything up here.

I'm using Twitter Bootstrap's popovers. My popovers seem to be working for elements that I manually type into my HTML document - but NOT the elements that I dynamically generate via Javascript / Ajax.

For example, the popover seems to work if I manually add this directly to my HTML document:

<p rel=popover data-content='It is so simple to create a tooltop for my website!' data-original-title='Twitter Bootstrap Popover'>hover for popover</p>

But what I really need is for my dynamically generated elements to have popovers. I use an XMLHttpRequest to send a request to a PHP file, and then grab the responseText and display it. When I add this line of code to my aforementioned PHP file:

 echo "<p rel=popover data-content='It is so simple to create a tooltop for my website!' data-original-title='Twitter Bootstrap Popover'>hover for popover</p>";

... surely enough, the words "hover for popover" appear - but the popover itself doesn't work!

This has been driving me nuts for some time and it would be incredible if someone could lend me a helping hand! I've also added the JQuery function I'm using to enable Bootstrap's popovers below, for what that's worth.

$(function (){
$("[rel=popover]").popover({placement:'left'});
}); 

I've done a thorough search of similar problems and the best I could find was this link. But that link doesn't seem to have any solutions either. Thanks in advance again!

UPDATE:

Fixed! Many thanks to everyone who helped out. My problem was that the function was being called BEFORE the elements were added into the Document Object Model. There are multiple possible fixes - I simply tested out the solution by shifting the popover function to the END of the Ajax function and it worked!

Answer

nickaknudson picture nickaknudson · Aug 14, 2012

You need to call $("[rel=popover]").popover({placement:'left'}); AFTER the elements are in the DOM.

UPDATE

If you are using jQuery

$(element_selector)
  // load results into HTML of element_selector
  .load('your/php/file')
  // when done, initialize popovers
  .done(function(){
    $("[rel=popover]").popover({placement:'left'});
  });

OR a catch all for jQuery ajax requests

$.ajaxComplete(function(){
    $("[rel=popover]").popover({placement:'left'});
  });