Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery on mousedown not working on dynamically generated elements

So i'm trying to create a js/css "wave game" like tower defense ones. When all the pre-generated enemys from first wave are dead, it spawns the second wave and so on.

So far so good. The problem is that i just can't attack mobs dynamically spawned within second wave.

I used to try .live() in similar cases, but its deprecated, so i'm trying .on(), as instructed

$('.enemy').on('mousedown' , function(event) {

//attack code

}

Its working fine for initial mobs (1st wave) but it still just not working on dynamic mobs (>= 2nd wave)

Help, guys, please?

like image 711
Sarchophagi Avatar asked Aug 14 '26 15:08

Sarchophagi


2 Answers

You need to specify an element that is already there when the DOM is created. In the parameters, you specify the elements you want to add the mousedown method. By simply assigning $('.enemy'), it will attach the method to those that are already present in the DOM.

$('body').on('mousedown', '.enemy', function(event) {

    //attack code

}

As Wex mentioned in the comments, instead of writting $('body') you should use the container's name (the container which wraps the .enemy elements. This way, when a .enemy element is added, the event doesn't need to bubble all the way up to the body tag.

like image 196
VVV Avatar answered Aug 16 '26 03:08

VVV


The binding '.on()' works only with the content that created earlier then the script ran. So one solution could be you bind the event to the parent element.

    $('.PARENT_ELEMENT').on('mousedown', '.enemy', function(event){
    // your code here
    }

That should do it.

like image 21
danieltmbr Avatar answered Aug 16 '26 04:08

danieltmbr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!