2

After I prepend a div I would like to alert on clicking it, but I cannot seem to adress it. Do I have a typo here or is there another reason why this does not work?

http://jsfiddle.net/K6EbM/1/

$(".newsbilder").click(function () {
    var lbox = '<div class="ansicht_gross" style="height:100%; width:100%; background-color: green;">remove</div>';
    $("body").prepend(lbox);
});

$(".ansicht_gross").click(function () {
    alert(1);
});
Coffeehouse
  • 505
  • 1
  • 3
  • 15

5 Answers5

2

Elements with the class .ansicht_gross will not be available while registering event for the same. so in that context you have to delegate event for its closest static parent to make your code working. This kind of process is called as Event delegation

Try,

$("body").on('click',".ansicht_gross",function () {
    alert(1);
});
Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130
2

You need to use event delegation here since your div has been added dynamically:

$('body').on('click', '.ansicht_gross', function () {
    alert(1);
});

This will helps you to bind click event to the newly added .ansicht_gross div.

Fiddle Demo

Felix
  • 37,892
  • 8
  • 43
  • 55
2

You need event delegation for dynamically added dom elements.use :

$("body").on('click','.ansicht_gross',function () {
  alert(1);
});

Working Demo

Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
2

You could also do this :

$('.newsbilder').click(function () {
    var lbox = $('<div /* attributes */>alert on click</div>');
    $("body").prepend(lbox);
    lbox.click(function () {
        alert(1);
    });
});

It's worth noting that event delegation leads to extra operations which are not necessarily required, that is to say, whenever you click the BODY element, jQuery browses the clicked child's ancestors in order to check whether any of them matches the passed selector, as it happens, '.ansicht_gross'.

Knowing this, imagine that a grumpy user starts clicking very quickly anywhere in the application... =D Well, it's a bit twisted but, keep in mind that the more there are selectors to check, the more there are comparisons to perform. So, careful usage required.

Further reading : Are there any drawbacks to listen events on document level in jQuery?

Community
  • 1
  • 1
1

Use on.

$(".newsbilder").click(function () {
    var lbox = '<div class="ansicht_gross" style="height:100%; width:100%; background-color: green;">alert on click</div>';
    $("body").prepend(lbox);
});

$('body').on('click',".ansicht_gross", function () {
    alert("1");
});

DEMO

msapkal
  • 8,268
  • 2
  • 31
  • 48