Warface
Warface

Reputation: 5119

On('click') jquery doesn't work after page loaded with load() function

Is use a cookie to know which page to load inside my DIV

if($.cookie('logged') == null){
    $('#auction-form').load('pages/login.php');
}else{
    $('#auction-form').load('pages/bid.php');
}

But inside the login.php page, I have another link that would trigger another load() function which is not working.

$('.register-btn').on('click',function(){
    $('#auction-form').load('pages/register.php');
});

The .register-btn class is a link which should trigger the function above. I know this might be something that it's because when the login.php page is loaded, it's not in the DOM so the .register-btn can't be seen. How I could delegate the script on a page that is loaded from a load() function ?

Upvotes: 2

Views: 6591

Answers (1)

Venkata Krishna
Venkata Krishna

Reputation: 15112

Use event delegation using .on()

$(document).on('click','.register-btn',function(){

instead of

$('.register-btn').on('click',function(){

Since .register-btn does not reside on the DOM(dynamic element), you cannot bind the event directly.

For dynamic elements, the syntax is:

$(parentselector).on('event', 'selector', yourFunction)

Note that parentselector needs to be a Non-dynamic always DOM present element

Upvotes: 8

Related Questions