A quick look at the "Related" section on this very page will give you links to all the information you need. In summary, the browser (unless it's Firefox) prevents it and the easiest workaround is to insert a zero-width space character (Unicode U+200B
) after the inserted <span>
element. As well as being a very ugly hack, this does have the problem of keeping track of and removing these zero-width spaces once they're no longer required.
I've updated your jsFiddle to use this approach but without any code to remove the zero-width spaces:
For background, here's a list of relevant questions/answers:
- Setting the caret position to an empty node inside a contentEditable element
- https://stackoverflow.com/a/15814297/96100
- Placing caret outside of inserted tag in ContentEditable
- Setting the caret position to an empty node inside a contentEditable element
I need a stock answer for this, it comes up so often...