Reputation: 1995
I'm a JQuery noob trying to make a horizontal scrolling div
, which scrolls to the sides when the user hovers near the edges (specifically the leftmost or rightmost 10%). When the mouse leaves the div
, though, I want it to stop animating entirely. The problem I'm experiencing is that it DOES stop, but then it immediately restarts again.
Here's a JSFiddle link that illustrates my issue. Moving your mouse to the left or right 10% of the div gets it scrolling (all good), and then moving it back to the middle 80% stops it (all good). Moving the mouse out of the div displays "EXITED" so we know it registered the mouseleave
function (all good), and the animation promptly stops if it was going (all good).
BUT, the animation immediately restarts again! And I have no idea why. It obviously isn't calling the animate functions again because the "EXITED" is still displayed at the bottom, but I don't know how else it could start animating again.
Does anyone know why this is happening? And more importantly, does anyone know how to make the animations stop permanently after mouseleave
?
And for bonus points: is there a way to tell the animation "slow to a stop" instead of just stopping immediately?
Upvotes: 0
Views: 768
Reputation:
To answer your first question, this problem is solved by putting the stop function inside of the main function as such:
$(".scroller").mousemove(function(e){
var h = $('#innerscroller').width()+1130;
var offset = $($(this)).offset();
var position = (e.pageX-offset.left)/$(this).width();
if(position < 0.10) {
$(this).animate({ scrollLeft: 0 }, 5000);
$(".status").html(' Percentage:' + position.toFixed(2) + ' lefting');
} else if(position > 0.90) {
$(this).animate({ scrollLeft: h }, 5000);
$(".status").html(' Percentage:' + position.toFixed(2) + ' righting');
} else {
$(this).stop().clearQueue();
$(".status").html(' Percentage:' + position.toFixed(2));
}
$(".scroller").mouseleave(function(e){
$(this).stop().clearQueue();
$(".status").html('EXITED');
}); });
Here is the modified jsfiddle
The .stop() function will only go to an abrupt stop so if you really want the slow to a stop I would use a technique like found in this post
Upvotes: 1
Reputation: 16223
I think it's happening because you're calling .clearQueue()
after .stop()
instead of before, if you change it to be the other way around it seems to work:
$(this).clearQueue().stop();
Upvotes: 1