0

AFAICT this should work but it doesn't. Using jQuery 1.9.0, I have the following:

<html>
    <head>
        <script type="text/javascript" src="js/libs/jquery-1.9.0/jquery.min.js"></script>
        <script type="text/javascript">

            $(document).ready(function() {
                $("button").click(function() {
                    $("#area").html("<p>click me</p>");
                });

                $("p").on("click", function() {
                    alert($(this).text());
                });
            });

        </script>
    </head>
    <body>
        <p>some text</p>
        <button>Create me</button>
        <div id="area"></div>
    </body>
</html>

Why does clicking on "some text" bring the alert but clicking on the generated "click me" not? I thought the whole point of .on() was to enable event handlers on dynamically generated code. According to Click event doesn't work on dynamically generated elements this should work but it doesn't. See http://jsfiddle.net/ymUYy/1/

Community
  • 1
  • 1
JohnC
  • 97
  • 4
  • [Please read the jQuery `.on()` documentation where delegation is clearly explained.](http://api.jquery.com/on/) – Sparky Apr 04 '13 at 01:46
  • Please don't frame the question in as "generated elements" because it is part of the confusion that makes people misunderstand how event delegation works. The `.on()` docs describe it pretty clearly I think. The element where you attach the event _must_ exist at the time you attach the event. The idea is that events from elements that are _below_ that may occur later, and those elements may not yet exist. – Dave Methvin Apr 04 '13 at 02:57

1 Answers1

3

.on() isn't a drop-in replacement for .live(). You need to use the event delegation syntax:

$('#area').on('click', 'p', function() {
    ...
});
Blender
  • 289,723
  • 53
  • 439
  • 496
  • 4
    The important thing to know about delegation is that the elements you apply `.on()` to must exist at the time you call it, the elements named in the 2nd argument can be added dynamically. – Barmar Apr 04 '13 at 01:46