My application includes a typeahead feature when a user is typing into a comment box. In a similar fashion to Facebook’s and google+’s it will perform a lookup of users and suggest them as tags on the fly.
When a user selects one of the offered tags it gets entered into the input area as an element.
I decided to use a conenteditable div for this, but have come across a few issues.
It turns out that firefox wont delete the inserted elements when they are set to contenteditable false whereas every other major browser does.
In order to work around this I have set the inserted ‘user’ tags as contenteditble=true and wrote a quick jquery workaround to solve this issue.
It works perfectly apart from one major issue. If there are multiple tags in the area and the first of them is not proceeded by any text, then when the user deletes the final one (assuming deletion with the backspace key from right to left) the caret gets positioned incorrectly following that final deletion.
Typing again appears to then return the position to normal.
This issue only occurs in Firefox
Here is a jsFiddle showing the issue:
http://jsfiddle.net/gordyr/PESky/
Place your cursor at the end of that last tag and then hold down the backspace key until all elements are removed. You will see that the cursor/caret moves up and out of position.
It is quite possible that this is actually a bug in firefox itself, however I am looking for a workaround of some kind as without this automatic element deletion with javascript, the don’t get removed at all.
Many thanks
It appears that FF leaves some dirt behind, but you can clean it up by adding:
This will check if the innerText of the contenteditable only contains spaces or newlines/breaks. If it does, just empty it. Seems to work in my test: http://jsfiddle.net/cBZ7k/
Side note: you should probably use
keydowninstead ofkeypressfor webkit support. Also,e.whichis enough to get the keyCode, jQuery normalizes this event property for you.