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

Amir
  • 79
  • 1
  • 5
  • 1
    someone just asked this question like 10 minutes ago: http://stackoverflow.com/questions/7429374/attaching-jquery-to-buttons-after-document-ready – Ben Lee Sep 15 '11 at 10:40
  • There might be an answer for you here. http://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements – amsandun Mar 12 '15 at 18:30

4 Answers4

1

Take a look at live()

$('#touchMe').live('click', function() {
Niko
  • 26,516
  • 9
  • 93
  • 110
1

Try -

$('#touchMe').live('click',function(){
alert ("WORKED");
});
ipr101
  • 24,096
  • 8
  • 59
  • 61
1

Instead of

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

use

$('#touchMe').live('click', function(){
alert ("WORKED");
});
Ghazanfar Mir
  • 3,493
  • 2
  • 26
  • 42
  • 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? – Amir Sep 15 '11 at 12:11
  • 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 :) – Ghazanfar Mir Sep 15 '11 at 12:14
  • 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 – Amir Sep 15 '11 at 12:24
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.

roselan
  • 3,755
  • 1
  • 20
  • 20