Reputation: 125
I have a hover effect with jquery on a menu, it works fine but if you move the mouse over the items a few times faster the animation then goes on as much times you got in that zone, sorry if I can't explain my problem as I wish, what I need is some kind of delay so if you move the mouse lots of times the function will trigger just one time and then you wait like 1sec for get the effect again. thanks!
$(".border").hover(function(){
if($(this).next('.sous_menu').is(':visible')){
$('.sous_menu').closest('.border').removeClass('border').addClass('border_active');
}else{
$(this).toggleClass('border_active border', 500);
}
});
Upvotes: 1
Views: 110
Reputation: 567
If I understand the question properly, I believe this is what you're looking for...
$(document).ready(function() {
var canMove = true;
$("#moveme").hover(function() {
if(canMove) {
canMove = false;
$(this).css("left", "50px");
setTimeout(function() { canMove = true; }, 1000);
}
}, function() {
$(this).css("left", "10px");
});
});
jsfiddle here
The on hover code above will only run once the "cooldown" of 1000 (1 second) has been reached. Alternativly, you could have the set canMove
to true on the hover exit, this would make sure that the code only runs once per hover (even though this should already be the case).
Upvotes: 0
Reputation: 46380
You can check if the function has been executed the last second by adding a checker var and chaning it on a timeout:
// the first time should always be allowed
var allow = true
$(".border").hover(function(){
// if 'allow' is false, return without doing anything
if(!allow) {
return;
}
// the function is now gonna execute, don't allow
// other events from executing the function
allow = false;
// executing the function
if($(this).next('.sous_menu').is(':visible')){
$('.sous_menu').closest('.border').removeClass('border').addClass('border_active');
}else{
$(this).toggleClass('border_active border', 500);
}
// after a second of the execution of the function, set allow to
// true again to allow other events from executing the function
setTimeout(function() {
allow = true
}, 1000)
});
Upvotes: 0
Reputation: 773
Try adding a delay()
and stop() before the toggle.
The stop()
will stop any ongoing animation preventing virtually endless animation. while the delay()
will delay it for how many milliseconds you put.
$(this).stop()delay(1000).toggleClass('border_active border', 500);
Upvotes: 0
Reputation: 896
You can take a look to this plugin : hoverIntent jQuery Plug-in as describe in this question Delay jquery hover event?
Upvotes: 1