In the last weeks I was trying to figure out a way to make things scroll nicer and that doesnt affect negatively the performance. When I start I didnt know exactly what was the result I wanted, so after a few frustrated attempts coding something by my self I start looking for some sort of custom easing functions, how they works, etc. This is how I got to this blog about Physics and JavaScript, specifically to this article about car suspension (Hooke’s Law). And I thought it may works great on scrolling.

After trying several times to use this on scrolling I finally made my first successful attempt, and it was pretty much what I had in mind: http://code.juan.me/demos/springy/basic/html/. In the demo you can see on the left, the green squares are being eased with the spring effect, the one on the right has no easing (so you can see the difference).

Looking at the first attempt (and being an Android user) I realized there was something familiar with it, it took me a while to realize that it was exactly what the Messages App of iOS 7 does, so of course I couldnt resist to do this: http://code.juan.me/demos/springy/messages/html/. And now we can say that Apple is using car suspension physics in some of their Apps (?).

I also wanted to try this in a sort of more real use case, so I made two more demos using a grid prototype, this one with images: http://code.juan.me/demos/springy/grid-prototype/html/ and this one more clean in white: http://code.juan.me/demos/springy/grid-prototype-2/html/

The Code

Note: Ill only go through the parts of code related to the spring effect of the first demo, if you want to see more how the demo was made feel free to take a look at the full code.

First at all we define the spring properties, the params stiffness and friction talk by them self. The threshold option is basically how long you want to keep the spring working, so like if acceleration is equal or less than 0.03 it will stop. The inMotion array specifies which of the squares are currently in motion.

When the scrolling starts we set the flag of motion for each square in true and we also call core.stepScrolling using requestAnimFrame.

Here we go through all the square elements, if it is still in motion we calculate and set the acceleration, velocity and new position for it. When the squares are not in motion we call core.completeScrolling.

And finally, on completeScrolling we reset all our variables and stop the Request Animation Frame that was calling core.stepScrolling.

Update — Jan 27, 2014.

I put these demos in a GitHub repo because some people wanted to contribute with a few improvements in performance :)

https://github.com/juancabrera/demos