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

2
  • How are you loading the HTML? Does jQuery not add the click event? Maybe you have an older version of jQuery? Commented Apr 21, 2015 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 Commented Apr 21, 2015 at 21:15

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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.
It's the same issue, you either have to re-bind the bootstrap functions or you have to convert to event delegation.
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.,

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.