Text Selection Particle Effects
Creating particle effects based on text selection using the Web Animations API.
After reading Playing With Particles Using the Web Animations API I wondered if it would be possible to create particle effects based on the user selecting text.
You could whip up something quick by listening for a mousedown
event and adding the particles based on the mouse position. It looks cool, but I wasn’t too happy because it doesn’t look as neat, and it doesn’t work if you’re doing selection with the keyboard.
There are two events we need to make this work:
selectstart
selectionchange
selectstart
is needed to reset our initial top
position. We use this to check if we’re moving up or down in our selection. Once a selection is finished, and we start again, and the value can be reset.
selectionchange
is fired any time our selection changes, and we’ll use this to generate our coordinates for our particles. This is where most of the work is done.
Here’s how it goes:
- We start selecting some text, and
selectstart
is fired, where we reset our initialtop
value tonull
selectionchange
is then fired where get the current selection usingwindow.getSelection()
- With this, we get the range of text using
selection.getRangeAt(0)
, followed by the bounds usingrange.getClientRects()
- The bounds now contain a
DOMRectList
with our selections, and we’re only interested in the first and last item in this list - If our initial
top
value isn’t set (as it’s been reset byselectstart
) then we assign it to thetop
value of the firstDOMRect
item in the list - We check if the
left
value has changed in the most recentDOMRect
item in the list - We check if we’re moving up or down the page with our selection
- If we’re moving down, we use the most recent
DOMRect
in the list, otherwise, we use the first - If we’re moving left, our
x
position will be theleft
value, otherwise, we’ll useright
- Our
y
value will be they
value of our chosen bounds, plus the height of the selection so the particles appear below the text
Thanks to Louis Hoebregts for a great article. I had a bunch of fun and confusion getting this to work, but it was a welcome distraction.