How do I stop a bouncy JQuery animation? - javascript

In a webapp I'm working on, I want to create some slider divs that will move up and down with mouseover & mouseout (respectively.) I currently have it implemented with JQuery's hover() function, by using animate() and reducing/increasing it's top css value as needed. This works fairly well, actually.
The problem is that it tends to get stuck. If you move the mouse over it (especially near the bottom), and quickly remove it, it will slide up & down continuously and won't stop until it's completed 3-5 cycles. To me, it seems that the issue might have to do with one animation starting before another is done (e.g. the two are trying to run, so they slide back and forth.)
Okay, now for the code. Here's the basic JQuery that I'm using:
$('.slider').hover(
/* mouseover */
function(){
$(this).animate({
top : '-=120'
}, 300);
},
/* mouseout*/
function(){
$(this).animate({
top : '+=120'
}, 300);
}
);
I've also recreated the behavior in a JSFiddle.
Any ideas on what's going on? :)
==EDIT== UPDATED JSFiddle

It isn't perfect, but adding .stop(true,true) will prevent most of what you are seeing.
http://jsfiddle.net/W5EsJ/18/
If you hover from bottom up quickly, it will still flicker because you are moving your mouse out of the div causing the mouseout event to fire, animating the div back down.
You can lessen the flicker by reducing the delay, however it will still be present until the delay is 0 (no animation)
Update
I thought about it and realized that there is an obvious solution to this. Hoverintent-like functionality!
http://jsfiddle.net/W5EsJ/20/
$(document).ready(function() {
var timer;
$('.slider').hover(
/* mouseover */
function(){
var self = this;
timer = setTimeout(function(){
$(self).stop(true,true).animate({
top : '-=120'
}, 300).addClass('visible');
},150)
},
/* mouseout*/
function(){
clearTimeout(timer);
$(this).filter(".visible").stop(true,true).animate({
top : '+=120'
}, 300).removeClass("visible");
}
);
});

You could use .stop() and also use the outer container position
$(document).ready(function() {
$('.slider').hover(
/* mouseover */
function(){
$(this).stop().animate({
top : $('.outer').position().top
}, 300);
},
/* mouseout*/
function(){
$(this).stop().animate({
top : $('.outer').position().top + 120
}, 300);
}
);
});
​
DEMO
Hope this helps

Couldn't reproduce your issue but I believe that hover is getting called multiple times. To work around this you can check if the div is already in animation. If yes, then don't run another animation again.
Add following piece of code to check if the div is already 'animating':
if ($(this).is(':animated')) {
return;
}
Code: http://jsfiddle.net/W5EsJ/2/
Reference:http://api.jquery.com/animated-selector/

I understand the problem and reproduced it, it happens when hovering from the bottom up. The hovering with the mouse is what's causing the problem since the animation function will be called when the mouse hovers over the image. You need to control what happens here by using mouse enter and mouse leave, check out a similar example: Jquery Animate on Hover

The reason it's like that is because the hover is getting queued up causing it to slide up and down multiple times. There's a plug-in called hoverIntent which fixes the issue. http://cherne.net/brian/resources/jquery.hoverIntent.html
If you do decide to use hoverIntent, the only thing you have to change in your code is .hover > .hoverIntent

Related

Navbar hover if mouse

I have this Javascript code that i got on another thread on Stackoverflow but there is a small gap of about 1px when the mouse hits this between the navbar header and the actual dropdown then the dropdown will disappear.
I grabbed this code as if there is a mouse I would like it to hover, however if it is on mobile with no mouse then I would like the user to click to open the dropdown.
//NAVBAR HOVER IF MOUSE, IF NOT CLICK
$('body').on('mouseenter mouseleave', '.dropdown', function(e) {
var _d = $(e.target).closest('.dropdown');
_d.addClass('show');
setTimeout(function() {
_d[_d.is(':hover') ? 'addClass' : 'removeClass']('show');
$('[data-toggle="dropdown"]', _d).attr(
'aria-expanded',
_d.is(':hover')
);
}, 300);
});
Is there anyway I can add a delay to this to give the user time to get over this pixel window?
I'm not very experienced with Javascript/JQuery but thought the number towards the end (300) would be a timeout as this seems to be the end of the function so I increased this to 60000 but this did not make any difference.
Any help is appreciated. This is also developed within Bootstrap if that makes a difference.
Thanks for all of your help.
As you pointed to the CSS Kosh Very I had a look and added this code which has fixed my issue:
.dropdown > .dropdown-menu {
margin: 0;
}
This has cleared the issue, thanks for your help.
For delay you can use the [Jquery.delay()][1] Method. It will simply post delay before any event that comes after the call to .delay e.g.
$( "div.first" ).slideUp( 300 ).delay(500).fadeIn(2000)

Loop horizontal scrolling of two divs with mousewheel and buttons

I need to loop horizontal scrolling of wide block. Also I need to controll scrolling with mousewheel and buttons.
I have created working demo on codepen.
Demo on CodePen
Here I use Endless.JS for loop scrolling (works with 2 divs and more) and jquery.mousewheel for mouse wheel support. Also I write some code for arrows. On hover -> block start scrolling with animation.
animate({scrollLeft:'+=40'}
This method works great with mouse wheel but I got some trouble with arrows. After I have scrolled first few divs other div become blinking and works like artifact in game :) (see demo)
Can you help me? Maybe I need to use some other method or lib?
Thanks a lot.
You should probably avoid jQuery.animate here. Not exactly sure what causes the problem, but using timeouts seems to work fine. That way, you also have more control over the delay and animation speed. http://codepen.io/anon/pen/zGbLB
var timeout;
function loop_next(){
timeout = window.setTimeout(function() {
container.scrollLeft(container.scrollLeft() + 2);
loop_next();
}, 20);
}
function loop_prev(){
timeout = window.setTimeout(function() {
container.scrollLeft(container.scrollLeft() - 2);
loop_prev();
}, 20);
}
function stop(){
window.clearTimeout(timeout);
}

Why is my jQuery transition is glitchy?

I have a jQuery transition with a css overlay that will work fine if the user mouses over for a second or more....however if the user mouses over quickly then the overlay text stays put without the overlay background. Here is my jQuery code:
$(".cascade-t1").hover(function(){
$(".cascade-corner").fadeOut();
$(".overlay-t1").animate({"left": "-300px"}, 300, function(){
$(".cascade-overlay-content").fadeIn(200);
});
}, function(){
$(".cascade-corner").fadeIn();
$(".cascade-overlay-content").fadeOut(200, function(){
$(".overlay-t1").animate({"left": "130px"}, 300);
});
});
Here is the script in action
It looks like the issue is that you don't fadeIn() the .overlay-t1 text until the mouseenter animation is done, and on mouseleave you fadeOut() the text out right away before the animation. When you move your mouse in and out faster than initial the animation the code will fade out the text and then fade it in again (the issue you're seeing).
One possible solution is to slightly alter your bottom (mouseleave) function to resemble your top (mouseenter) function more closely. Something like:
$(".cascade-corner").fadeIn();
$(".overlay-t1").stop(true, true).animate({"left": "130px"}, 300, function () {
$(".cascade-overlay-content").fadeOut(200);
});
The .stop() is there to keep the animation from playing over and over when someone spams the box.
FIDDLE DEMO
Not sure how jquery animate works under the hood but it's possible it's using javascript to animate instead of css transitions. The benefit of css transitions is that it does all of the animation calculations before the animation begins and is hardware accelerated. Javascript is at the mercy of the scheduler at a very high level so it will always be choppy.
Try jquery transit.
http://ricostacruz.com/jquery.transit/

jQuery .stop() breaks subsequent animations

I'm trying to make an accordion-like menu with jQuery, but it refuses to cooperate: http://jsfiddle.net/vrcpK/1/
Here is my JavaScript:
$('#submenu div.submenu').hover(function() {
$('.submenu-head', this).addClass('visible');
$(this).siblings().each(function() {
$('div.submenu-body', this).stop(true).slideUp('slow');
$('p.submenu-head', this).removeClass('visible');
});
$('div.submenu-body', this).stop(true).slideDown(500);
}, function() {
$('.submenu-head', this).removeClass('visible');
$('div.submenu-body', this).stop(true).slideUp('slow');
});​
When you hover over an item twice, the menu dies and slowly shrivels up. After that, it lethargically reveals a third of the content.
I suspect it is a problem with my .stop(true) calls, but I can't figure out any other way to keep the menu from becoming gelatin after moving the mouse over it.
Any help would be greatly appreciated!
Seems like the height is set to whatever it is when hover out... try reseting the height to auto when the slide up is complete...
$('div.submenu-body', this).stop().slideUp('slow', function() {
$(this).height('auto');
});

jQuery's stop() seems to be blocking animations that haven't been queued yet

How does jQuery's stop() actually work?
If you look here (http://jsfiddle.net/hWTT6/), when you hover over the main blue box it should fade to red, and when you hover off it should fade back. The problem is it will completely fade to red (and then back to blue) even if the mouse has hovered off before the first fade was complete. The problem can more clearly be seen with the slide effect. Hover over the slide "button" and the main box will slide to blue, hover off, it will slide back. But try hovering on and off and on and off, before the first animation has completed. You'll see that all four animations are carried out. I included both examples here to show it is not just a problem with one effect or something.
I thought this would be easily fixed by adding a stop before the animations, as shown commented out in the code. But, if I do this the current animation will stop and the following one will never start. Almost as though stop is blocking an animation that is occurring after the call to stop.
What am I missing here?
Thanks.
You are missing that .stop() accepts two arguments. Both boolean, indicating:
- clearQueue (first)
- jumpToEnd (second)
So by calling $('#foo').stop( true, true ).doSomeOtherStuff() you should get your desired goal.
Reference: .stop()
The problem is the CSS is getting messed up by stopping at arbitrary points.
The fadeIn(), fadeOut(), slideUp() and slideDown() move from the current state to a new one and then revert to that - not to the original CSS.
You need to fix the CSS back in to a usable state to continue with after the .stop(), or more clearly specify the animation targets.
As the others have said, you can get the CSS to the correct position, by ensuring that when you stop the animation, it jumps to the end of it, rather than leaving everything in an arbitrary state.
UPDATE:
Take a look at the code in this update of your demonstration: http://jsfiddle.net/hWTT6/5/
It might not be exactly how you want it to perform, but the trick, if you do not want the animation to run its course, is to get the animation back in to a state that it can continue from in the way in which you desire.
$(function() {
$('#fade')
.mouseenter(function() {
$('#fg_fade').stop().animate({ 'opacity': 0 }, 'slow', function() {
$('#fg_fade').css('height', '100%');
});
})
.mouseleave(function() {
$('#fg_fade').stop().animate({ 'opacity': 1, 'height': '100%' }, 'slow');
});
$('#slide_fire')
.mouseenter(function() {
$('#fg_fade').stop().animate({ 'height': 0 }, 'slow', function() {
$('#fg_fade').css('opacity', 1);
});
})
.mouseleave(function() {
$('#fg_fade').stop().animate({ 'height': '100%' }, 'slow', function() {
$('#fg_fade').css('opacity', 1);
});
});
});
You could set the stop() options to (true, true) so that you cancel all events in cue and jump to the end of the previous animation. look at the fiddle:http://jsfiddle.net/hWTT6/4/
The stop method can be called in the following difference ways:
.stop(true);
//Same as:
.stop(true, false); //Empty the animation queue only
//Or
.stop(true,true); // Empties the animation queue AND jumps to the end
//Default
.stop()
//Same as
.stop(false,false);
There may be a better way using .animate instead: Demo Here
$(function() {
$('#fade')
.mouseenter(function() {
$('#fg_fade').stop().css('height', '10em').animate({'opacity' : '0'}, 'slow');
})
.mouseleave(function() {
$('#fg_fade').stop().css('height', '10em').animate({'opacity' : '1'}, 'slow');
});
$('#slide_fire')
.mouseenter(function() {
$('#fg_fade').stop().css('opacity', '1').animate({'height' : '0'}, 'slow');
})
.mouseleave(function() {
$('#fg_fade').stop().css('opacity', '1').animate({'height' : '10em'}, 'slow');
});
});
This way the animation stops when you want it to and still runs the next animation.
The problem with doing .stop then slideUp/slideDown or fadeIn/fadeOut is that the animation can end prematurely and keep an incorrect height/opacity.
The problem is caused by the way fadeIn, fadeOut etc. work. You may expect them to fade between 0 and 1. However, in reality they fade between 0 and whatever the "baseline" opacity is. You can see this here:
http://jsfiddle.net/hWTT6/7/
You'll notice I set the initial opacity to .5. Now when I call fadeIn it does not fade all the way in to 1 it fades to my baseline of .5. Your problem occurs when you stop the animation prematurely, the "baseline" becomes whatever the opacity is at the time it is stopped. Now when you call fadeIn on mouseleave it tries to fade to this new baseline and finds it is already there. You can see this illustrated by going here:
http://jsfiddle.net/hWTT6/8/ (original, but with .stop)
If you place your mouse over slide and then remove it half-way through the animation, it will stop in the middle. Now place your mouse back over slide and wait for the animation to complete. If you now remove your mouse, you will see that it slides back down to the place where the first animation was stopped. That is because this is the new "baseline".
The way that you would solve this is actually to replace fadeIn, fadeOut, etc. with a more explicit animation. For instance, use fadeTo to tell it to fade between 0 and 1:
http://jsfiddle.net/hWTT6/6/
Notice that since I am telling it to fade to 0 or 1 everything works. A similar thing could be done to replace slideUp and slideDown using animate.

Categories

Resources