0

I have a page and defined my java script functions in a custom.js file ( I'm using jQuery ). I put JS file at end of body before </body> tag

My page have a div element like this:<div id="userinfo"></div> when my page load, my JS file fetch an external page to that.

external page have a element like this<div id="login"></div>

in my JS file, I defined a function that when user clicked the login a modal window load an show the login form to the user.

but when i load the external page, my JS file does not work!! it seems that can't find the element.

guide me Please! :)

Some part of custom.js file:

jQuery(document).ready(function($) {

 $('#userinfo').load('CustomerOptions.asp');

  (function() {
     $('#login').click(function(event){
         // something to do
     });
  })();

});
1
  • You said you put that in your <body></body> tag? Also, do you have an example fiddle or anything? Commented Jul 17, 2012 at 16:56

4 Answers 4

1

You may try to use on:

$('#userinfo').on('click','#login',function(){
    //Click logic here
});
$('#userinfo').load('CustomerOptions.asp');
Sign up to request clarification or add additional context in comments.

Comments

1

The current version of the code is trying to bind click event handler to #userinfo even before its available in the DOM (since the element is added to DOM via load asynch call).

Try this:

$('#userinfo').load('CustomerOptions.asp', function() {
     $('#login').click(function(event){
         // something to do
     });
});

Comments

0

It not works because you have assigned a event to #login before it is present in DOM. For cases like this you must use "live" events. Live events do not requires that the target element is present in DOM.

jQuery(document).ready(function($) {
   $('#userinfo').load('CustomerOptions.asp');

  $('#userinfo').on('click','#login',function(event){
     // something to do
  });
})();

EDIT: As pointed by @ManselUK, 'live' is deprecated, 'on' must be used.

Comments

-1

Or as an alternative you could use .live() instead of .click().

http://api.jquery.com/live/

1 Comment

live is deprecated. on would be a better options.

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.