Jquery on mousedown not working on dynamically generated elements
Solution 1
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.
Solution 2
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.
Comments
-
Sarchophagi almost 2 years
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?
-
Wex about 10 years+1 Might be better to use the container for your enemies instead of
body
though. -
VVV about 10 years@Wex Absolutely so it doesn't need to bubble all the way up.
-
kryptonkal about 10 yearsI was about to post this as well. Try binding the event to $(document) or $('body')