Over the weekend, I added emoji shortcuts just below my comment form. To do this, I had to render the emoji options using Lucee CFML; and then, I had to apply the selected emoji to the
In the past, I've looked at using the
Selection properties of input elements -
Using this new-found understanding, my emoji shortcuts can be easily augmented with the new behavior by making sure that I insert the emoji at whatever the
selectionEnd property is at the time of the interaction. This ends up being great for keyboard accessibility reasons as well.
To this in action, I have a
textarea followed by some
button elements. When you click on one of the
button elements, it will take the
textContent of the
button and insert into the
textarea value at whatever the last known
selectionEnd property contains:
As you can see, when the user clicks on one of the
button elements, all we're doing is grabbing whatever the current
selectionEnd property is and using that to slice-and-dice our input string. Then, we update the
selectionEnd property so that the next focusing of the input will bring the caret to just after our inserted text.
ASIDE: Even through some emoji require more than one codepoint, the
lengthproperty appears to handle our offsets property (since it will show a length of 2 for our multi-codepoint emoji).
Now, if we run this code in the browser, we can move our caret around and then use simple keyboard navigation to insert text back into the
input at the previously-selected location:
As you can see, even after I blur the input using either keyboard navigation or a mouse click, when I go to insert the selected text-token, I'm inserting it at the last known
selectionEnd property. Super elegant! And, so much easier than trying to track and record the last known location using additional events.
Want to use code from this post? Check out the license.