Reputation: 101
I am trying to simulate a collision detection by firing an event if all of the following conditions are present:
The issue is that the eventListener is rapidly firing. I tried using a debounce function, but it only delayed the rapid fire.
Javascript/Jquery
$(document).keydown(function(e) {
if (e.which == '39') {
$('#mainSprite').attr("class","cycleR");
}
else if (e.which == '37'){
$('#mainSprite').attr("class","cycleL");
}
else if (e.which == '38'){
$('#mainSprite').attr("class","cycleUp");
document.getElementById("mainSprite").addEventListener("animationend", function(){
var pos = $(document).scrollLeft();
if( pos >= 25 ){
alert("Jump");
}
}, false);
}
else {
$('#mainSprite').removeClass("cycleR");
}
});
$(this).keyup(function(){
$('#mainSprite').removeClass();
});
Here is a link to the site where I am trying to implement the code. The little character will hop up and "hit" a marker to trigger an event. Please note, user will need to be able to scroll to multiple locations down the page and still have the event listener fire (aka "collide" with multiple objects).It essentially works like GPS. If the user has scrolled to the x-coordinate, and the animation has placed the character at the y-coordinate, fire an event.
Upvotes: 1
Views: 560
Reputation: 707318
On every keydown where e.which == 38
, you are adding yet another event listener for animationend
. That means after a few keys, you will have multiple listeners and thus your callback will be called multiple times.
You have to either add the eventListener only once ever or you have to remove the event listener after it fires.
If using jQuery, you can use the .one()
method of installing the event handler so that it will be automatically removed after it fires.
Upvotes: 2