Pasted garbage says to contentEditable;

A contentEditable, pasted garbage and caret placement walk into a pub

submited by
Style Pass
2021-07-22 22:30:05

Pasted garbage says to contentEditable; "Hey! I'd really like to become part of you" and contentEditable says back; "Not so fast, you! First we got to rinse you down!". And thus begins a story of how to make contentEditable take in a good ol' paste, parse that paste for anything we might not want, put the result of that parsing into the right place in contentEditable and place the caret just after that paste. Sounds easy, right? Right.

By default, contentEditable takes in just about anything you'd like to give it. If you copy text from anywhere that also has mark-up and styles (like a Word document) and then paste it into the contentEditable, it would gladly take all that mark-up and styles as well. But this isn't a great user experience if you're building a content editor like I am, so the best solution is to parse that paste and remove anything you might not want - which in my case was to remove all styles and only allow certain mark-up.

Alright so let's create a simple contentEditable that also listens to the Paste event. I'll be doing this in ClojureScript as it is my favourite language, using Reagent for the React goodness as this is a React app, but all of this also applies for good ol' regular JS and React.js.

Leave a Comment