Skip to content Skip to sidebar Skip to footer

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 goo

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.


Solution 3:

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;
});

Post a Comment for "Jquery On Mousedown Not Working On Dynamically Generated Elements"