0

How can I make an appended element clickable? In this case, clicking "Hello" should change the background of #div1.

<!DOCTYPE html>
<html>
<head>
    <script src="http://code.jquery.com/jquery-latest.min.js"></script>
    <script>
    $(document).ready(function(){
        $("button").click(function(){
            $("#div1").append("<p>Hello</p>");
        });
        $("p").click(function(){
            $("#div1").css({"background":"#0ff"});
        });
    });
    </script>
    <style>
    #div1 {
        background:#ff0;
        height:100px;
        margin:0 0 50px 0;
        }
    p {cursor:pointer;}
    </style>
</head>
<body>
    <div id="div1"></div>
    <button type="button">Click Me!</button>
</body>

Thank you!

Kobbe
  • 316
  • 1
  • 13

2 Answers2

0

Use event delegation using .on()

$(document).on('click', 'p', function(){
    $("#div1").css({"background":"#0ff"});
});

Since you've added the html <p>Hello</p> dynamically, events cannot be attached directly, you have to use event delegation as shown above.

Venkata Krishna
  • 14,926
  • 5
  • 42
  • 56
0

use below code. it is called event-delegation . read more here

$(document).on('click','p',function(){
        $("#div1").css({"background":"#0ff"});
});
Nishit Maheta
  • 6,021
  • 3
  • 17
  • 32