user3377041
user3377041

Reputation: 103

Bootstrap Popover Not Working When Loaded With Ajax

When I load Bootstrap popver content with ajax, the popover is not showing.

Javascript:

var id = 1;
$.post("load.php?pageid",
        {
          pageid:id;
        },
        function(data,status){
         document.getElementById("body").innerHTML=data;
        });

HTML response:

<a href="#" id="example" class="btn btn-danger" rel="popover" data-content="It's so simple to create a tooltop for my website!" data-original-title="Twitter Bootstrap Popover">hover for popover</a>
<script>  
$(function ()  
{ $("#example").popover();  
});  
</script> 

When I place the HTML response above directly in the <body id="body"></body> code, the popover works fine. I dont understand what is going wrong here.

Upvotes: 8

Views: 13219

Answers (3)

Rahma Samaroon
Rahma Samaroon

Reputation: 700

with the help of jQuery you can initialize all things that needs to be initialized using

$(document).ajaxSuccess(function () {
    $("[data-toggle=popover]").popover();
    $("[data-toggle=tooltip]").tooltip();
    // any other code
});

inspired from Olaf Dietsche answer

Upvotes: 8

batoutofhell
batoutofhell

Reputation: 1309

<script>$(function () {  $('[data-toggle="tooltip"]').tooltip()});</script>

Add this at the end of whatever you are loading in with ajax. You should already have this somewhere to opt-in to the tooltip, but put it again to re-initialize the tooltip.

Upvotes: 5

Jason Reid
Jason Reid

Reputation: 870

The problem is that you're setting up the popover inside of the function $(). Rather than

$(function ()  
{ $("#example").popover();  
}); 

It should be just

$("#example").popover();  

Or perhaps better

$(document).ajaxComplete(function() {
  $("#example").popover();
});

The reason being that any function inside of $() is run when the document is first finished loading, when the "document ready" event is fired. When that code is pasted inside of the original HTML, it works because it's present when the document finishes loading.

When it's the response from an AJAX call, it won't run inside of $(), because the "document ready" event already fired some time ago.

Upvotes: 16

Related Questions