4

How do I make JQuery treat new elements in the same way that the original elements in a html file are treated? For example, consider the following example:

<!DOCTYPE html>
<html>
    <head>
        <title>simple click to switch</title>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
        <script type="text/javascript">
            $edit = "<div>edit</div>";
            $(document).ready(function () {
                $("div").click(function () {
                    $(this).after($edit);
                    $edit = $(this);
                    $(this).remove();
                });
            });
        </script>
    </head>
    <body>
        <div>switch me</div>
    </body>
</html>

I expected this block of JQuery to allow me to toggle between the divs "switch me" and "edit", on clicking. However, the result is, it recognises the original div, allowing a single "toggle". But the newly added div is not recognised by JQuery. The div can only be toggled once. How do I solve this problem?

1 Answers1

3

For dynamically added elements you need to use event delegation to register handlers

$(document).on('click', 'div', function () {
                $(this).after($edit);
                $edit = $(this);
                $(this).remove();
            });

Demo: Fiddle

Also read this

Community
  • 1
  • 1
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • Very nice. Thank you for the resource as well. If it's not too much off topic, why is the "on" function necessary? Is there any semantic or practical reason why JQuery doesn't automatically allow new elements to be captured? –  Aug 13 '13 at 00:46
  • An explanation of why would be nice – Ruan Mendes Aug 13 '13 at 00:46
  • @user2593666 see the question I've linked as a duplicate – John Dvorak Aug 13 '13 at 00:48
  • @user2593666 Event delegation handles bubbling events at a parent node that is not dynamic. jQuery assigns the handler to the entire document, and when the event fires, it checks if it matches the selector you gave before firing the handler. In your example, you were setting handlers on the elements that existed at the time only – Ruan Mendes Aug 13 '13 at 00:48