0

i'm kinda new to scripting so this might be a bit basic, but i couldn't find an answer anywhere. To improve my webpage loading time I made some HTML element load (via AJAX) and inserted only when a certain button is clicked, using the jquery .html() function. That worked, but now all the jquery commands which referred to that element don't seem to apply. I'm guessing it's because the original commands were loaded before the new HTML?

For example, code like this:

$(document).ready(function(){   
$('#myButton').click(function(){
$('#placeHolder').html('<div id="touchMe">click me</div>');
});
$('#touchMe').click(function(){
alert ("WORKED");
});
}

How do I make the #touchMe.click command apply to the new incoming HTML?

thanks a lot

2

4 Answers 4

1

Take a look at live()

$('#touchMe').live('click', function() {
Sign up to request clarification or add additional context in comments.

Comments

1

Try -

$('#touchMe').live('click',function(){
alert ("WORKED");
});

Comments

1

Instead of

$('#touchMe').click(function(){
alert ("WORKED");
});

use

$('#touchMe').live('click', function(){
alert ("WORKED");
});

3 Comments

OK! thanks, works (after updating jQuery to the correct version - live() only exists from 1.3 on). This is a simple example code we've discussed here. The real deal includes many more commands. So, for general knowledge, would you say correct and best practice is using live() instead of all commands that deal with html that would arrive later on?
Yes, I think live seems to be consistent and reliable as compared to others. But I can't say anything on behalf of JQuery Developers :)
Thanks a lot. to all you guys - not sure i know exactly how this whole voting / feedback thing works yet, but you were all very helpful and efficient. cheers
0

you use .live() or .delegate() function instead of click.

$(document).ready(function(){   
  $('#myButton').live('click', function(){
    $('#placeHolder').html('<div id="touchMe">click me</div>');
  });
  $('#touchMe').live('click', function(){
    alert ("WORKED");
  });
}

note: the live on "mybutton" is not necessary in this example.

Comments

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.