Reputation: 357
Following is the code for a box, which has sliding options(.box-options) animating out of the box on mouseenter with added delay of 1000ms
i want to stop the animation(or sliding it's options out) if mouse is out of that box before completing 1000ms
I don't want to use any external plugin, Only JQuery I have.
$('.box').on('mouseenter', function(){
$(this).find('.box-options').stop().delay(1000).animate({
right: "-42"
},400);
});
Upvotes: 1
Views: 205
Reputation: 955
I would make use of CSS animations. Not only do they require less work to get up and running, but browsers are optimised like crazy for CSS and perform far more efficiently than an equivalent Javascript tween effect.
For something like this, I would recommend having the on mouseenter event apply a class to the box-option elements that triggers a CSS animation.
$('.box').on('mouseenter', function() {
$(this).find('.box-options').addClass('active');
}).on('mouseleave', function() {
$(this).find('.box-options').removeClass('active');
});
Of course if you were clever about it, you could use the CSS psuedo selector :hover
in combination with -webkit-transition
to achieve this all without javascript. See my JSFiddle which uses absolutely no Javascript. This is definitely the superior way of managing this effect.
Upvotes: 0
Reputation: 4068
You can do the following, assuming you want to freeze the animation in its tracks if the mouse stops hovering over the box.
var animInProgress = false;
$('.box').on('mouseenter', function(){
$(this).find('.box-options').animate({
right: "-42"
},400);
animInProgress = true;
setTimeout(stop_animation,1000);
});
$('.box').on('mouseleave', function(){
// if the mouse leaves the box before the animation is finished
if(animInProgress) {
// stop the animation
$(this).find('.box-options').stop()
// or do something else (revert to original pos?)
}
});
function stop_animation() {
animInProgress = false;
}
Upvotes: 1