Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery not working on AJAX loaded html content

I have a PHP admin dashboard in which am using bootstrap theme. We know it have inbuilt jQuery objects like drop-down menu, collapse, tabs, etc., And it all will work if we just added bootstrap js file.

Now the problem is when I get contents from ajax call and display it on my page, all javascript controls which loaded via ajax are not working.

Am using this ajax call for all my inner pages display. So it may have any bootstrap javascript control on loaded HTML.

So how can I fix this dynamically on every ajax call. My ajax loading javascript is below

$('a').bind('click',function(event){
    event.preventDefault();
    $.get(this.href,{},function(response){
        $('#app-content-body').html(response)
    });
});

Note : My problem is not in my above code. Actual problem is bootstrap javascript controls not working when I load html content from above code

like image 291
Vinoth Kannan Avatar asked Apr 21 '15 21:04

Vinoth Kannan


1 Answers

jQuery is only aware of the elements in the page at the time that it runs, so new elements added to the DOM are unrecognized by jQuery. To combat that use event delegation, bubbling events from newly added items up to a point in the DOM that was there when jQuery ran on page load. Many people use document as the place to catch the bubbled event, but it isn't necessary to go that high up the DOM tree. Ideally you should delegate to the nearest parent that exists at the time of page load.

Change your click event to use on(), provided your version of jQuery supports it;

$(document).on('click', 'a', function(event){

If you're using jQuery older than version 1.7 use delegate():

$('body').delegate('a' , 'click', function() {

Note the operator order, they are different with on() reading a little more logically.

like image 137
Jay Blanchard Avatar answered Oct 27 '22 12:10

Jay Blanchard