Problem with binding event handler to a dynamically created element

Viewed 332

I have just started learning HTML, CSS and jQuery and I am new. I searched for binding event handlers to dynamically added elements and I found out I have to use the parent of the dynamic element as the static selector and add the dynamic element after the event method ( Correct me if I am wrong).
$(staticAncestors).on(eventName, dynamicChild, function() {});
But I do not know why the code below does not work when I change :

  1. $("#p1") with $(this)
    or
  2. $(document) with $("div")

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
</script>
<script>
$(document).ready(function(){
    $("div").click(function(){
        $(this).html('<p id="p1" style="background: red;">Paragraph one</p> <p>Paragraph two</p>').css('margin', '15px 15px 15px 15px');
    });
    $(document).on('click', '#p1', function(){
        $("#p1").css('background-color', 'blue');
    });
});

</script>
</head>
<body>
<div> It's a div. </div>
</body>
</html>

1 Answers

According to Jquery Docs https://api.jquery.com/on/

By default, most events bubble up from the original event target to the document element (In your case from #p1). At each element along the way, jQuery calls any matching event handlers that have been attached. A handler can prevent the event from bubbling further up the document tree (and thus prevent handlers on those elements from running) by calling event.stopPropagation().

Here is your working code.

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
</script>
<script>
$(document).ready(function(){
    $("div").click(function(){
        $(this)
        .html('<p id="p1" style="background: red;">Paragraph one</p> <p>Paragraph two</p>')
        .css('margin', '15px 15px 15px 15px');        
        
    });

    $("div").on('click', 'p', function(event){
        event.stopPropagation();
        $(this).css('background-color', 'blue');
    });
});

</script>
</head>
<body>
<div> It's a div. </div>
</body>
</html>

Related