Possible Duplicate:
javascript not working in the new part when loading a new part using jquery and HTML 5
I loaded another HTML page into a div of the main HTML page using Ajax. The page loaded fine, but when I try to apply jQUery to the loaded page, nothing works.
$('.mainDiv').click(function(ev) {
ev.preventDefault();
var url = $(this).attr('href');
$('.secondDiv').load('http://127.0.0.1:8000'+url);
});
I tried using a simple alert function called on all links to see if it works, but the alert appears only on the main page links, even though the .js file is linked to both pages.
$('a').click(function(){
alert('hey');
});
How can I fix this? Would using .live() or .on() instead of .load() fix the problem?
Using $('body').on('click', 'a', function(event){...}) would work.
Because on is called on the <body> you don't need to worry about the event getting wiped out when you load in new content.
If you would like to scope this event on a specific set of anchors I would suggest name spacing with a class in the second parameter using something like
$('body').on('click', '.mainDiv .secondDiv a', function(event){...})
By setting this once in a bootstrap you can reduce a lot of complexity within your code. Now all you need to do is load in the content; there is no need to define a callback inline as you've extracted out the event logic.
$('a').on(...) will not work as the DOM element it's bound to may get wiped out, or is not on the page at the time of the call. The 2nd parameter of the on call is used to reference any new elements appearing under the root element (body in this case).
This is what you need to do:
$('.secondDiv').on('click', 'a', function() {
alert('hey');
});
So basically every dynamic anchor tag loaded in secondDiv will be binded to this function automatically. Otherwise what you could have done is:
$('.secondDiv').load('http://127.0.0.1:8000'+url, function(){
$(this).find('a').click(function(){
alert('hey');
});
});
But I would not suggest you the latter, if the first one works fine for you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With