Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 819
user3377041 Avatar asked Mar 09 '14 01:03

user3377041


3 Answers

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.

like image 179
Jason Reid Avatar answered Nov 07 '22 09:11

Jason Reid


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

like image 24
Rahma Samaroon Avatar answered Nov 07 '22 09:11

Rahma Samaroon


<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.

like image 25
batoutofhell Avatar answered Nov 07 '22 11:11

batoutofhell