I have implemented 2 static images with fixed positions at the edges of the screen (one on the right and one on the left). The logic I want to achieve is that when a user scrolls more than 100 pixels from the top, these edge images should move back by 50 pixels. Moreover, I want them to return to their original position when the user scrolls back to the top. I attempted to use a boolean value which switches between true and false when the images retract or reappear, but it doesn't seem to be working as expected. Why?
userHasScrolled = false;
$(document).ready(function(){
$(window).scroll(function(){
if ($(window).scrollTop() > 100) {
$(".rightstatic").animate({marginRight:'-50px'}, 900);
$(".leftstatic").animate({marginLeft:'-50px'}, 900);
userHasScrolled = true;
}
});
});
if($(window).scrollTop() <= 0 && userHasScrolled) {
$(".rightstatic").animate({marginRight: '+50px'}, 400);
$(".leftstatic").animate({marginLeft:'+50px'}, 400);
userHasScrolled = false;
}
Edit:
$(document).ready(function(){
$(window).scroll(function(){
if ($(window).scrollTop() > 100) {
$(".rightstatic").animate({marginRight:'-20px'}, 900);
$(".leftstatic").animate({marginLeft:'-20px'}, 900);
} else if($(window).scrollTop() <= 0) {
$(".rightstatic").animate({marginRight: '+0px'}, 400);
$(".leftstatic").animate({marginLeft:'+0px'}, 400);
}
});
});
Although this code somewhat works, there is a significant delay in the functionality. It takes more than a minute after reaching the top for the images to retract.
Edit 2: Finally, after throttling the function, it now operates smoothly. Thank you @TomaszBubała for the assistance.