jquery onclick not working on element from .load() function

2.1k Views Asked by At

I have a PHP snippet in a separate file which I am loading in a javascript file using jquery:

let signUpMode = $(".modal");
  signUpMode.load("login_signup_popup.php");

This works because I am able to show this on screen. However, this snippet contains a button which I would like to click in the same javascript file where I loaded the snippet. something simple like:

$(".signupbtn").on("click", function(){
    console.log("signed Up");
  });

This click is, however, not working. signupbtn is a div element in the snippet. Somehow I am missing an extra step since jquery seems to not be recognizing the elements in the snippet.

2

There are 2 best solutions below

1
tom On BEST ANSWER

Lazy loaded elements are not recognized from eventhandlers which are already initialized. So you have to set the event on a parent. This should work:

$(document).on('click', '.signupbtn', function(){ 
    console.log("signed Up");
});
0
Kavelin On

https://api.jquery.com/load/

You could use the complete function to check if it has loaded, or you could just put the button function inside there.

  let signUpMode = $(".modal");
  signUpMode.load("login_signup_popup.php", function() {
    $(".signupbtn").on("click", function() {
      console.log("signed Up");
    });
  });