0

So I am on a hunt to try and figure out the best ways of optimizing the Jquery .animate(scrollTo:value) function. Take this example:

$('#returnToTop').on('click', function(){
        $('html, body').animate({
            scrollTop: 0
        }, 'slow');
    });

Here you have a div which acts as a "Top" button that when clicked, scrolls the page back to the top. Now on complicated pages, this is rather jerky and not smooth. I was wondering if any jQuery ninjas could enlighten us as to what exactly the animate function does. On simple pages, it's nice and smooth.

Now, I assume that it probably does some calculations that walks down the DOM, so when it's complicated, it takes a while and looks jumpy. So here's the heart of the matter:

are there any steps we can take, as developers to provide jQuery with the precise parameters that would make it's calculations simpler, therefore making the animation smoother. There are probably specific values that are important that if provided, would provide a significant speedup.

Does anyone have any insight?

Thanks.

1 Answer 1

4

To jQuery, "slow" is an amount of time (600ms to be precise). If it is a big page, it needs to be jumpy to go to the top in 600ms.

If you want to make this animation with a constant speed independent of page height, set the duration to t = offsetTop / k to walk aproximatelly k pixels per second, where offsetTop is something like $(clickedElement).offset().top.

jQuery also has some plugins to do it in a straight way.

Sign up to request clarification or add additional context in comments.

2 Comments

This actually was far smoother, but due to the complexity of my page, it seems that it's still a bit jerky. I was hoping someone could enlighten us a bit of the inner workings of the animate function to try to isolate what is causing the rendering slowdown. If we don't get any more responses, I will mark this as correct.
You can try some javascript/css profiling (with Chrome Developer Tools for example) to see what is slowing down your code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.