6

I have some code like this:

$('.play').on( 'click', function(){
    console.log('click');
});

The .play element is dynamically created with $('.game').html('<span class="paly">Play</span>') method. However, I have nothing in my console log when I'm clicking on this span. What am I doing wrong?

Thanks.

PS: I am using jQuery 1.7.1

1
  • 1
    this answer may help, i believe you are using on() like bind() not like on()
    – T I
    Jan 13 '12 at 15:57
11

Don't use live() - it has been deprecated. Instead use on(), but use it on a parent element to delegate the event to, like this:

$('#parentOfPlay').on('click', '.play', function(){
    console.log('click');
});
3
  • That would be the other around: $("#parentOfPlay").on("click", ".play", function() {});. Jan 13 '12 at 16:00
  • 1
    Yep, that does the trick. If I understant right I need to use $(document).on with dynamic content an $('.selector').on with non-dynamic content, right?
    – bbrodriges
    Jan 13 '12 at 16:06
  • 3
    Yes - although if it's dynamic content, it should be the nearest non-dynamic containing element. If you use document you may see a performance decrease. Jan 13 '12 at 16:08
1

You can use live (which is now deprecated in 1.7.1 so you really shouldn't use it) or do it with on, but you where doing 'on' wrong.

$(document).on('click', '.play', function(){
    console.log('click');
});
0

Here is a good break down of what to use and when. https://stackoverflow.com/a/8845306/1139444

.on will give you the affect you are looking for but you need to do it on the document selector and put the class selector into the .on call.

$(document).on( 'click', '.play', function(){
    console.log('click');
});
0

the .play selector is looking for a container with that class, so you'll need to generate the code with:

$('.game').html('<span class="play">Play</span>');
0

.html() sets the contents of all blocks that have a class named game to Play. You have not created any class .play hence doing $(".play") yields nothing. The click function is not bound to anything and nothing is shown on the console. Try doing $(".game").on("click",function(){});

-1

Try with

$(document).on('click', '.play'
    function(){
        console.log('click');
});
1
  • .live() is deprecated and must be avoided. Use .on() or .delegate() Jan 17 '12 at 11:15
-2

Try this:

$('.play').live( 'click', function(){
    console.log('click');
});
-2

Are you sure the ".play" element is already there when executing your code? Or maybe it's only created later in code.. It might be an ordering issue.

edit: If you want it dynamic, use 'live' instead of 'on as suggested by others:)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.