2

I am appending an li to a ul, for example:

$(".vocab-list").append( $('<li onclick="play_sound(\''+val['audioURL']+'\');" class="vocab-word" id="vocab_' + val['id']+ '"><img width="230px" height="230px" src="' + val['imageURL'] + '" /><div><i class="fa fa-play-circle"></i>' + val['word'] + '</div></li>').hide().fadeIn(600));

Now I am trying to do something onclick so using the following but its not working

$( ".vocab-word" ).click(function() {
  alert( "Handler for .click() called." );
});
Jake
  • 3,326
  • 7
  • 39
  • 59

2 Answers2

6

The issue is generally the dynamic addition ... it wasn't there when the click event was set to monitor.

Try ...

$(document).on("click", ".vocab-word", function() {
  alert( "Handler for .click() called." );
});

This will allow your code to monitor the event at the document level, regardless of what changes.

UPDATE:

The concept is to monitor above where the element will be added and I don't know your code so can't guarantee other elements you can attach to. It is possible, depending on the complexity of your code to cause performance issues using the $(document).on() code ... try $("body") or lower HTML elements.

rfornal
  • 5,072
  • 5
  • 30
  • 42
  • don't use document on, please read here `http://api.jquery.com/on/` `Event performance` section – waki Dec 21 '14 at 15:37
  • 1
    OK ... I'll give you a maybe on performance, but the concept is to monitor above where the element will be added and I don't know his code so can't guarantee other elements. – rfornal Dec 21 '14 at 15:38
2

use

$(".vocab-list").on('click', '.vocab-word', function() { 
alert( "Handler for .click() called." ); 
);

See http://api.jquery.com/on/, Handling Events and Understanding Event Delegation

pwdst
  • 13,909
  • 3
  • 34
  • 50
waki
  • 1,248
  • 2
  • 17
  • 27