Add span's with click events via jQuery

I am trying to add spans to a div via jquery. These spans should have an onclick event. The spans seem to be added, but the newly created elements' click events don't fire. I'm worthless at jQuery and am not sure what I'm missing. Any help is appreciated.

Here is some relevant code:

<script type='text/javascript'>
$(window).load(function(){
     $('#Match .WordSpan').click(function() {
          alert($(this).html());
          $('#Match').append('<span>me too!</span><br/>').html();
          $("span:last").addClass("WordSpan").html();
     });
});
</script>

<input type="text" id="WordInput"  />
<div id="Match">
     <span class="WordSpan">click me!</span><br />
</div>

I have it in a fiddle here.

What I am hoping the code will do is, after clicking on the hard coded "click me" span, another span will be added below. When clicked, that span will add another, saecula saeculorum.

Where have I blown it?

Answers


Using delegate performs better than using live:

$('#Match').delegate('span.WordSpan', 'click', function() {
    alert($(this).html());
    $('#Match').append('<span>me too!</span><br/>');
    $("span:last").addClass("WordSpan");
});

If using jquery 1.7+ then use on instead of delegate. jsFiddle example


Try this:

$('#Match .WordSpan').live('click', function()....

Fiddle: http://jsfiddle.net/maniator/kLJ3J/3/

I also removed those random html()'s at the ends. not sure why you had those there...


Starting in jQuery 1.7, do this:

 $('#Match').on('click','.WordSpan',function() {
      alert($(this).html());
      $(this).append('<span class="WordSpan">me too!</span><br/>');
 });

before 1.7 (but on or after 1.4.2 as noted by @Greg Pettit) do this:

 $('#Match').delegate('.WordSpan','click',function() {
      alert($(this).html());
      $(this).append('<span class="WordSpan">me too!</span><br/>');
 });

Also, instead of using a <br>, perhaps you could take care of that in your CSS, or by using an element other than span.

If you do that, you could use this form of creating elements:

$('<span>',{className:'WordSpan',text:'me too!'}).appendTo(this);

jQuery has built in optimizations for creating elements this way.


Need Your Help

Send emails using JavaMail from my own domain in AWS

email amazon-web-services dns smtp javamail

We have been sending email notifications (outbound only) to our customers using a gmail address donotreply@gmail.com and we got smtp host and port configured in our server.

Make a DIV reveal upwards onClick

javascript jquery html css onclick

I found a topic for revealing a DIV upwards but as I am no Javascript expert, I am wondering how I can make this work onClick rather than on hover?