Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery on('click', ...) not working on appended element

I have a div that I append with the following code:

function generateBall(){
    var colors = ["fe0ba5", "00c0ff", "21f1a5", "f13e21", "e819fb", "3ae319", "ff9900", "512e5e", "284184"];
    var width = $('.reaction_area').width() - 40;
    var height = $('.reaction_area').height() - 40;
    var a = Math.floor(Math.random()*(width - 40 + 1) + 40);
    var b = Math.floor(Math.random()*(height - 40 + 1) + 40);
    var size = Math.floor(Math.random()*(32 - 24 + 1) + 24);
    var color = colors[Math.floor(Math.random() * colors.length)];

    $('.reaction_area').append('<div class="ball_2" style="left: '+a+'px; top: '+b+'px; height: '+size+'px; width: '+size+'px; background: #'+color+'" data-id="'+wave+'"></div>');
}

And then I have this:

$('.ball_2').on('click', function(){
    $(this).remove();
    wave--;
});

And it's not working. I have other elements that I append like that and clicking them works, why this doesn't?

I've tried also with $('document').on('click', '.ball_2', function(){ //code }); and it didn't work either.

like image 941
ALSD Minecraft Avatar asked Jan 07 '23 02:01

ALSD Minecraft


1 Answers

That would be $(document) (without the quotes).

$('.ball_2').on('click', ...) doesn't work because the element .ball_2 doesn't exist yet at the time of execution. However, $(document).on('click', '.ball_2', ...) works because it puts the handler on an ancestor element and takes advantage of a phenomenon called "event bubbling". In simple terms, an ancestor is considered clicked when a descendant is clicked.

like image 166
Joseph Avatar answered Jan 08 '23 16:01

Joseph