5

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

Vinoth Kannan
  • 242
  • 5
  • 16
  • How are you loading the HTML? Does jQuery not add the click event? Maybe you have an older version of jQuery? – Halcyon Apr 21 '15 at 21:13
  • my HTML loading script is above and it's working fine. I mean when I load HTML content inside my div javascript not working on that loaded HTML – Vinoth Kannan Apr 21 '15 at 21:15

1 Answers1

6

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.

Community
  • 1
  • 1
Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119
  • no am not talking about above click event. I mean if ajax loaded html having some bootstrap nav menu, tabs, dropdown, etc., that all not working. – Vinoth Kannan Apr 21 '15 at 21:20
  • It's the same issue, you either have to re-bind the bootstrap functions or you have to convert to event delegation. – Jay Blanchard Apr 21 '15 at 21:22
  • 1
    Yes I know. I have to re-bind. But I don't know which all bootstrap javascript controls going to come after ajax load. So how to re-bind everything in Bootstrap? like dropdown, tabs, etc., – Vinoth Kannan Apr 21 '15 at 21:27