This was originally posted on my blog.
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:
selectstartselectionchange
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
selectstartis fired, where we reset our initialtopvalue tonull -
selectionchangeis 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
DOMRectListwith our selections, and we're only interested in the first and last item in this list - If our initial
topvalue isn't set (as it's been reset byselectstart) then we assign it to thetopvalue of the firstDOMRectitem in the list - We check if the
leftvalue has changed in the most recentDOMRectitem 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
DOMRectin the list, otherwise, we use the first - If we're moving left, our
xposition will be theleftvalue, otherwise, we'll useright - Our
yvalue will be theyvalue 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.
Top comments (0)