ALSD Minecraft
ALSD Minecraft

Reputation: 1501

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.

Upvotes: 4

Views: 1183

Answers (4)

Ali Panahian
Ali Panahian

Reputation: 315

use delegate :

 $('.reaction_area').delegate('.ball_2', 'click', function (event) {

  $(this).remove();
    wave--;
});

Upvotes: 1

EricMok
EricMok

Reputation: 11

add following line in generateBall() function. Because the div is created dynamically, so we should bind the function when it being create. And this statement can let every '.ball_2' got it own remove function, assume there may be more than one '.ball_2'.

$('.ball_2:last').on('click', function(){$(this).remove());});

Upvotes: 1

user2560539
user2560539

Reputation:

Since element with class ball_2 is generated dynamically.

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

Upvotes: 2

Joseph
Joseph

Reputation: 119847

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.

Upvotes: 5

Related Questions