2

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?

Community
  • 1
  • 1
Sarchophagi
  • 377
  • 2
  • 5
  • 20
  • 1
    If you are using dynamic elements, your will need to either bind the event to the new mobs or use mousedown event on enemy container – juvian Apr 22 '14 at 17:12
  • 1
    Answered so many times : http://stackoverflow.com/q/13984136/1636522. –  Apr 22 '14 at 17:18

3 Answers3

18

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.

VVV
  • 7,563
  • 3
  • 34
  • 55
4

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.

danieltmbr
  • 1,022
  • 12
  • 20
0

I made this google like drop down suggestions search box and I faced a problem similar to yours where there was suggestions disappearing before the re-direct happened. I overcame it by using and modifing vyx.ca answer:

var mousedownHappened = false;
var clicked_link;

$("#search-box").blur(function(e) {
    if (mousedownHappened)// cancel the blur event
    {
        mousedownHappened = false;
        window.location.href = clicked_link;
    } else {
        // no link was clicked just remove the suggestions box if exists
        if ($('#search-btn').next().hasClass('suggestions')) {
            $(".suggestions").remove();
        }
    }
});
//attaching the event to the document is better 
$(document).on('mousedown', '.suggestions a', function() {
    clicked_link= $(this).attr('href');
    mousedownHappened = true;
});
Anthon
  • 69,918
  • 32
  • 186
  • 246
Joseph
  • 1,458
  • 15
  • 20