1

I've been using jQuery for a while now but this problem has never happened before.

Basically, HTML:

<div class="button three"></div>
<div id="Content"></div> 

CSS:

.button.three {
 width: 50px;
 height: 50px;
 background: blue;
 }

.textBlock {
    background: orange;
    height: 20px;
    width: 20px;
}

jQuery:

$(document).ready(function () {

    $(".button.three").click(function() {
        $("<div class='textBlock'></div>").appendTo("#Content");
    });

    $(".textBlock").click(function() {
        alert("2");
    });

});

See the JSFiddle: http://jsfiddle.net/Brannie19/cQk8t/

Why doesn't this work?

---EDIT--- I was wondering why the click event on .textBlock wouldnt fire. The answers from dsaa and net.uk.sweet actually explained it to me, so thank you guys.

Brannie19
  • 87
  • 7
  • 4
    possible duplicate of [Events triggered by dynamically generated element are not captured by event handler](http://stackoverflow.com/questions/12829963/events-triggered-by-dynamically-generated-element-are-not-captured-by-event-hand) – Felix Kling Apr 14 '14 at 23:39
  • and [Event binding on dynamically created elements?](http://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – Felix Kling Apr 14 '14 at 23:39
  • 1
    Updated your [fiddle](http://jsfiddle.net/cQk8t/1/) You're assigning an event to an element that doesn't exist in the DOM. Instead, search the document for the element and action a function on finding. `$(".button.three").click(function() { $('#Content').append('
    '); }); $(document).on('click', '.textBlock', function(){alert("2");});`
    – dsaa Apr 14 '14 at 23:48

1 Answers1

2

You're trying to add a listener to an element which doesn't exist yet. The solution is to delegate the event to the parent element which does exist using the jQuery on method (see documentation):

$(document).ready(function () {

        $(".button.three").click(function() {
            $("<div class='textBlock'></div>").appendTo("#Content");
        });

        $("#Content").on('click', '.textBlock', function() {
            alert("2");
        });

    });

http://jsfiddle.net/YNWX8/

net.uk.sweet
  • 12,149
  • 2
  • 22
  • 39
  • I thought that was the problem because if I added the click event to the $("
    "), it would work. Thank you very much :) I couldnt figure out how to work it. I would upvote your answer but I cant yet because I dont have enough rep yet :(
    – Brannie19 Apr 15 '14 at 12:35
  • 1
    No worries. I upvoted you so hopefully you're on your way ;) – net.uk.sweet Apr 15 '14 at 12:41