0

I click on div with id="tube_clx".

This action appends to div with id="tube" a span with id="trash".

When I click on span with id="trash". I expect alert to pop, yet it does not.

What I'm doing wrong?

<div>
    <div id="tube_clx">[click div]</div>
    <div id="tube"></div>
</div>

<script type="text/javascript">
    $(document).ready(function () { 

        $('#tube_clx').on('click', function(){ 
            $('#tube').append('<span id="trash">[click span]</span>');
        });

        $('#trash').on('click', function(){ 
            alert('hi');
        });
    });
</script>
Jeffz
  • 1,957
  • 5
  • 30
  • 48
  • possible duplicate of [Events triggered by dynamically generated element are not captured by event handler](http://stackoverflow.com/questions/12829963/events-triggered-by-dynamically-generated-element-are-not-captured-by-event-hand) – Felix Kling Jun 22 '13 at 19:53
  • you are right @Felix Kling (dupe), but my demo code and (especially) adeneo fiddle and explanation makes this "bubbly problem" much better explained; having said that, if I came across answer mentioned by you (not that I did not look for it), this question would not be here – Jeffz Jun 22 '13 at 20:06

2 Answers2

2

The event handler is bound to any element with an ID of #trash, but as you haven't clicked #tube_clx yet, there is no such element in the DOM.
To attach the event to any future elements with the ID #trash, you have to use a delegated event handler, like so :

$('#tube').on('click', '#trash', function(){ 
    alert('hi');
});

Also note that it's not $('.tube_clx'), but $('#tube_clx'), as it's the elements ID.

FIDDLE

adeneo
  • 293,187
  • 26
  • 361
  • 361
0

$('#trash') is called before you append your span and it returns an result set, as #trash didn't exist when you called the selector, so your event handler isn't bound to any element.

Use event delegation and attach the event handler to your #tube element instead:

$('#tube').on('click', '#trash', function(){ 
Blender
  • 257,973
  • 46
  • 399
  • 459