Reputation: 403
I'm trying to implement a simple animation of a logo panel on top of the page scaling when scrolling past a certain point and up if it's scrolled back up. I used jquery's .animate()
function to change some css parameters. I also use .stop()
function to break scrolling listener so the whole animation works with no lag.
It's almost there, but I noticed there is some jerky lag happening during the animation. For example when I scroll down it scales down, but not all the way, just slightly and in a second jumps to the full scaled down position. The same happens on scrolling up - it scales halfway or even pauses slightly several times before scaling back up. What do you think could cause that?
Here is my code:
(function($) {
$(document).ready(function() {
var animScroll;
$(window).scroll(function() {
if ($(this).scrollTop() > 700) {
animScroll = true;
$('#menu').stop().animate({height: '50px'}, {
queue: false,
duration: 400
});
$('#toplogo').stop().animate({width: '150px'}, {
queue: false,
duration: 400
});
} else if ($(this).scrollTop() < 700) {
$('#menu').stop().animate({height: '85px'}, {
queue: false,
duration: 400
});
$('#toplogo').stop().animate({width: '300px'}, {
queue: false,
duration: 400
});
}
});
});
})(jQuery);
Upvotes: 0
Views: 595
Reputation: 15786
JQuery is not the fastest when it comes to animation. Below I used CSS. Please note I changed the flipping point at 300 pixels.
(function($) {
$(document).ready(function() {
var animScroll;
$(window).scroll(function() {
if ($(this).scrollTop() > 300) {
$('#toplogo').addClass("smaller");
} else if ($(this).scrollTop() < 300) {
$('#toplogo').removeClass("smaller");
}
});
});
})(jQuery);
.container {
height: 1000px;
}
#menu {
position: fixed;
top: 0;
}
#toplogo {
transition: all .2s ease-in-out;
}
#toplogo.smaller {
transform: scale(0.5, 0.5);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div id="menu">
<img id="toplogo" src="http://placehold.it/200">
</div>
</div>
Upvotes: 2