scrollingtutorial (1)

Imagine if the actors in a movie showed up a few scenes early.

How would their poorly timed entrance hurt the story? Well, it wouldn’t make for much of a story at all, only a set of miscues.

Similarly, as we scroll down a website, we expect the story to present itself in a calculated manner, appearing at the right moment. Here at Lemonly, we augment our interactive infographics with subtle fades in, entrances from stage right or stage left, animated introductions to tell the viewer, “This is for you.”

Or senior developer created our trusty, scroll-triggered animation solution below. I admire its legibility and quickness. Plus, it’s highly reusable. In most cases, only one line — noted in step two — needs an edit when transferring the code block to a new site.

So you can take full advantage of cued animations, let’s take this step-by-step:

1. When the website loads, run a function. We’ll call that function “setupDom”:

2. Gather the elements you’d like to animate, within your setupDom function (lines 4-7):

3. Then create objects that will hold each element and its distance from the top of the page. Note line 17: In step 5, we’ll create animations.elements in which we’ll push these objects. (lines 5-18):

4. Write the function to get each element’s distance from the top of the page (lines 21-31):

5. Create an object of animations, in which you can hold your array of elements (lines 21-23):

6. Write the function that will calculate scroll position and test whether it has moved past the top of each element (lines 22-42):

7. Write a function to run testScroll within your animations object, and call it when the user scrolls (line 4-5, and lines 24-26):

8. Add a function to recalculate each element’s distance from the top of the page when the site is resized (line 4-5, and lines 27-32):

(Note: The addClass function isn’t native to JavaScript. At Lemonly, we add it using prototype. See Josh’s post on addClass and other non-Jquery functions here.)

Voila! You’ve created a reusable block of code that will add an “animate” class to elements when they enter the viewport. Be sure to define the starting and ending points in CSS, your starting point being the element itself, and ending point being the element with an “animate” class.

Let us know if you have questions or offer your own solution to scroll-triggered animations by writing us here.