A Fade-in Effect for Text
I wanted an animation I could use to display poetry online. Poems use words themselves as a medium for art, so my goal was to distinguish words inside a poem from the regular prose around them. After combing Stack Overflow for prior art and inspiration, I came up with a working solution.
The first step is to split out each word into its own inline element. Next, hide them all from view. Finally, render those words sequentially in an order that achieves a pattern appropriate to the poem and its context. The pattern I wanted to replcate was falling snow.
The effect starts when a block of hidden text is scrolled high enough into view for the reader to notice an animation right away. If their focus is somewhere else, the effect will be awkward and partly over by the time they catch it.
Both the speed and style of the effect are customizable. You can break the poem up into lines instead of words; you can cascade the words from left to right or right to left; you can limit the effect to one line at a time or have the next line start flowing before the current one finishes.
Here’s this effect applied to “Masks” by Shel Silverstein:
She had blue skin, And so did he.
He kept it hid And so did she.
They searched for blue Their whole life through,
Then passed right by-- And never knew.
Under the hood, the code looks for paragraph elements tagged with a class called emerge
. A function splitLines()
takes the paragraph, wraps each word in a <span>
, and applies opacity: 0
to make them invisible but preserve the space that text will take up later. getLines()
then collects the spans into lists that correspond to each line of text. Later, when the page is scrolled past a predefined point – say halfway up the browser window – the effect is triggered and text is displayed line by line and span by span.
To embed the demo here, I applied the animation individually to each stanza of “Masks” and set a max-width
property to enforce line breaks. This way getLines()
knows where to stop each line of the poem.
You can download a self-contained demo page from this gist. Steal the effect to format poetry, represent fleeting thoughts, or do justice to beautiful memories.