Reputation: 53
i am new to jquery but love it already ( i am a php programmer).
i have just use the .load() function to load content from another page to a new page. i am able to load the contents.
However, i now wish to accesssome elements of the newly loaded content but i am not able to do this.
$(document).ready(function() {
$('#signin a').click(function() {
var url=$(this).attr('href');
$('#loginpostion').load(url + ' #loginform');
return false;
$('#closebox a').click(function() {
$('#loginpostion').removeClass()
return false;
}); //end click
i now wish to access the following A tag from the newly loaded page: #closebox a
Is there anything that i need to do to let Jquery know that the "newly loaded content" will now form part of the DOM of the current page
Upvotes: 0
Views: 69
Reputation: 9031
you could eidther use the complete callback metod on the load method, like:
$(document).ready(function() {
$('#signin a').click(function() {
var url=$(this).attr('href');
$('#loginpostion').load(url + ' #loginform', function() {
$('#closebox a').click(function() {
$('#loginpostion').removeClass()
return false;
}); //end click
});
});
});
or you could use a delegate/live (if you aren´t using jquery 1.7+), if you want all your #closebox a elements that exists on the page now or in the future (with jquery and ofcouse then you cant have and id of #closebox) then you could use:
$(document).ready(function() {
$(document).on('click', '#closebox a', click() {
$('#loginpostion').removeClass();
return false;
});
$('#signin a').click(function() {
var url=$(this).attr('href');
$('#loginpostion').load(url + ' #loginform');
return false;
});
});
Upvotes: 1
Reputation: 318302
load()
uses ajax, which is asynchronous so it loads in the background while your script keeps going. This means that when you are trying to access #closebox
on the next line in your script, it does'nt yet exist as it has'nt been inserted into the DOM yet. You'll have to wait until the load()
function is completed, and luckily load()
has a callback function for this. Also, whenever you use return, the script ends and returns, so you'll have to do:
$(document).ready(function() {
$('#signin a').click(function(e) {
e.preventDefault();
var url=$(this).attr('href');
$('#loginpostion').load(url + ' #loginform', function() {
$('#closebox a').click(function(e) {
e.preventDefault();
$('#loginpostion').removeClass();
});
});
});
});
Upvotes: 1
Reputation: 50797
You need to delegate the function to a static parent element that exists on page load. We refer to this as 'Bubbling' or 'Event Propagation'. in jQuery's latest version, we use the .on()
function to perform these actions.
$(document).on('click', '#closebox a', function(){
$('#loginpostion').removeClass()
return false;
});
Upvotes: 1
Reputation: 38131
Remove the first return false;
line from your $('#signin a').click()
handler function. It is causing execution to return before the second click handler (to #closebox a
) is bound.
Upvotes: 1