I’m fairly new to using JQuery and was just playing around. I’m trying to have an element fade in on the click of a button. If the users clicks the button again, while the element is still fading in, I want it to start hidden/invisible again. So I first stop all animations stop(true) then hide the element an let it fade in.
I can’t get it to work though. It seems like the second fade in starts with the opacity the element has at that moment and fades in from there. I’ve also tried to use css("opacity", 0) in stead of hide() but then the element just gets it’s opacity set to 0 and fadeIn doesn’t seem to work anymore.
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"> </script>
</head>
<body>
<script type="text/javascript">
$(document).ready(function () {
$("button").click(function () {
$("span").stop(true).hide().fadeIn(3000);
});
})
</script>
<button>FadeIn</button> <span>Hello, world!</span>
</body>
</html>
Using JQuery 1.7.2 and tried in Chrome and IE.
What am I doing wrong?
.stop(true)just stops the animation and leaves it wherever it was. If you were in the middle of afade(), then the object will be left with an opacity value in the middle of the fade.If you want to stop the animation and put the opacity in a known state, then you probably just want to set it to what you want it to start at.
.hide()setsdisplay: none– it doesn’t mess with the opacity.So, if you were in the middle of a
fadeOut()when you did the.stop(true), then you could just do.stop(true, true)and that will jump the current animation to the end, thus giving you a good place to start yourfadeIn()from.You could also stop the animation where it was and then fade from there to your full opacity with:
which is more generally what you want to do when you’re interrupting the previous animation.