1

I want to be able to click on a element I've dynamically created and create an alert, and I can't seem to figure it out. I've looked at a bunch of similar threads on how to use .on, but I can only get it to work for static elements. Thanks in advance!

<span id="about">About</span>

<div id="lhn"></div>

And JavaScript:

$(document).ready(function () {

    $("#about").click(function () {

        $("#lhn").append("<div id='#child'>Child</div>");

        $("#lhn").on("click", "#child", function () {
            alert("Child has been clicked");
        });

    });

});
fergusrm
  • 23
  • 5

4 Answers4

3

Bind the event outside your about click handler. also, your ID should be child not #child when creating the element:

$(document).ready(function() {
    $("#lhn").on("click", "#child", function () {
        alert("Child has been clicked");
    });

    $("#about").click(function () {
        $("#lhn").append("<div id='child'>Child</div>");
    });
});
tymeJV
  • 103,943
  • 14
  • 161
  • 157
1

You have multiple issues with the code that you have written.

Firstly

$("#lhn").append("<div id='#child'>Child</div>");

supposed to be

$("#lhn").append("<div id='child'>Child</div>");

Secondly - ID's in a HTML page are supposed to be unique

So replace

$("#lhn").append("<div id='child'>Child</div>");

with

$("#lhn").append("<div class='child'>Child</div>");

Third

I see you are already delegating the event, so move the click event to outside the click event . Otherwise events will be bound multiple times to the element on every click.

$("#about").click(function () {
    $("#lhn").append("<div class='child'>Child</div>");
});

$("#lhn").on("click", ".child", function () {
    alert("Child has been clicked");
});
Sushanth --
  • 55,259
  • 9
  • 66
  • 105
0

One technique I use for appending elements is to create the element, then append it.

var element = $("<div id='child'>Child</div>").appendTo("#lhn").on("click", function() {
    alert("Child has been clicked");
});
teynon
  • 7,540
  • 10
  • 63
  • 106
0

user this simple code,

$("#child).live("click",function(){
    alert();
});
Angela Taylor
  • 151
  • 1
  • 11