kenny kenny - 2 months ago 6
CSS Question

Why does my jquery take so long when animating on scroll?

I have a box that slides right 100px when you scroll 10px and slide back to it's default location if the scroll is less than 10px. The box does animate, however, there is a bit of a delay when it does. Can anyone help me figure this out?

HTML

<div id="nest">
<div id="box">

</div>
</div>


CSS

#nest {
width: 95%;
max-width: 1000px;
margin: auto;
background-color: orange;
height: 1000px;
padding-top: 150px
}

#box {
margin: 50px 0px 0px 0px;
width: 100px;
height: 100px;
position:relative;
background-color: green;
}


jQuery

jQuery(window).scroll(function() {
if (jQuery(this).scrollTop() > 10) {
jQuery('#box').animate({left:'100px'})


} else {
jQuery('#box').animate({left:'0px'})
}
});


My JSFIDDLE LINK
https://jsfiddle.net/ispykenny/m6ffj83g/1/

thanks in advance for your time and help!

Answer

The reason your animation is taking so long would be that the animate is running on every scroll event past 10px, and this is quite intensive on the client-side. There are a few options, either experiment with the .stop() functionality in jQuery, or write a a conditional if statement that checks if the animation will have started and only fires if it hasn't.

https://api.jquery.com/stop/

this is a handy resource.

var coin = false;

jQuery(window).scroll(function() {
  if (jQuery(this).scrollTop() > 10 && coin === false) {
    jQuery('#box').animate({left:'100px'});
    coin = true;
  } else if (coin === true && jQuery(this).scrollTop() <= 10) {
    jQuery('#box').animate({left:'0px'});
    coin = false;
}
});

try this!