Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Abhishek Dutta
3,529 PointsCalling .animate() in a conditional statement on a value generated from .scrollTop() in jQuery
Well Here's my issue. I have added some jQuery code in my project file to shrink the size of the logo when I scroll down in the window and restore it back to its original size i.e. 200px when I am again on top of the document.
Here's the code
$(document).ready(function(){
$(window).scroll(function(){
var y = $(this).scrollTop();
//console.log(y);
if(y > 0){
$(".logo img").animate({
width: "110px",
}, 500);
}
else{
$(".logo img").animate({
width: "200px",
}, 500).stop();
}
});
});//document.ready--end
This code runs shrinks the size of the logo exactly when I scroll down but when I scroll back up, I need to wait for some seconds and then only it restores the size of the logo back to 200px..
Any solutions for this
Thanks
1 Answer
Steven Parker
243,318 Points
The delay was caused by queued animations.
When more than one animation is called on the same element, the later animations are placed in the effects queue for the element. These animations will not begin until the first one completes.
Since you were triggering an animation on every scroll movement, each one was placed in the queue, but since they all had the same target result there was no visible change. But the delays still added up. And having a stop call immediately after the animation was adding some peculiar intermittent effects.
A solution to this is to retain the current state of the image, and only apply the animation when the state should be changed. A .stop call before the animation prevents a queue from building if the scroll is rapidly moved at the top:
$(document).ready(function(){
var shrunk = false; // is the image shrinking, or already shrunk?
$(window).scroll(function(){
var y = $(this).scrollTop();
if(y > 0 && !shrunk){
shrunk = true;
$(".logo img").stop().animate({width: "110px"}, 500);
}
else if (y == 0 && shrunk) {
shrunk = false;
$(".logo img").stop().animate({width: "200px"}, 500);
}
});
});
Abhishek Dutta
3,529 PointsAbhishek Dutta
3,529 PointsThanks .. That worked