Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript scroll based animation is choppy on mobile

I have 2 divs (left and right) and i want to scroll the left based on the right. https://jsfiddle.net/3jdsazhg/2/

This works fine on desktop, but when i change to mobile, it's not smooth anymore... This can be noticed very easily, by changing

_left.style.top = _content.scrollTop - (_content.scrollTop * ratioLeftRight) + 'px';

to

_left.style.top = _content.scrollTop + 'px';

Where it should act as a fixed positioned div

  1. I would like to know the exact reason why this isn't smooth... I know that it's not the animation. Simple animation on the div is smooth, the issue comes up when it's based on scroll.
  2. How can i make this animation smooth?
like image 814
Inc33 Avatar asked Oct 14 '16 07:10

Inc33


2 Answers

It's probably choppy because it's being fired ALOT when being scrolled, in fact i'm pretty sure IOS mobile pauses the javascript execution whilst the user is scrolling.

Instead I'd suggest using an interval, you could tweak the time between each interval to what feels good for your use-case.

Although it may seem intensive that it's firing this logic every X millisecond when using the scroll event you could be firing the event off hundreds of times per second, which is going to be far more intensive and noticeable to a user using a device with limit processing power.

(function () {
     var interval = null,

         //Currently set at 0.4 seconds, play with the code
         //and change this value to see what works best for 
         //this use-case
         time_between_interval = 400;

     setInterval(scrollLogic, time_between_interval); 

     function scrollLogic () {
         //The function body of what you're assigning 
         //to the scroll event.
     } 

     //I have omitted clearing the interval but you would want to do that, perhaps on page change, or something.

     //clearInterval(interval);
})();
like image 94
Lee Brindley Avatar answered Sep 24 '22 06:09

Lee Brindley


I finally managed to think out a solution.

From my point of view, i'm guessing the mobile view fires the scroll event less often and because we are scrolling the wrapper, we first scroll the whole page and then scroll back with js the left part and because it's different from the desktop version, this issue becomes visible...

The solution was to change the left side to fixed position, and substract from the top instead of adding to it.

_left.style.top = -(_content.scrollTop * ratioLeftRight) + 'px';
like image 31
Inc33 Avatar answered Sep 24 '22 06:09

Inc33