Mario Uher
Mario Uher

Reputation: 12397

Move selection after a DOM element

I'm currently building a Markdown editor for the web. Markdown tags are previewed in realtime by appending their HTML equivalents via the Range interface. Following code is used, which should be working according to MDN:

var range = document.createRange()
var selection = window.getSelection()

range.setStart(textNode, start)
range.setEnd(textNode, end + 2)

surroundingElement = document.createElement('strong')
range.surroundContents(surroundingElement)

var cursorRange = document.createRange()
cursorRange.setStartAfter(surroundingElement)

selection.removeAllRanges()
selection.addRange(cursorRange)

Firefox works: Some bold text

enter image description here

Chrome not: Some bold text

enter image description here

Any suggestions what could be wrong? Information on this subject are rare.


Answer

Thanks to @Tim Down, I fixed it using the invisible character workaround he describes in one of the links mentioned in his answer. This is the code I'm using now:

var range = document.createRange()

range.setStart(textNode, start)
range.setEnd(textNode, end + 2)

surroundingElement = document.createElement('strong')
range.surroundContents(surroundingElement)

var selection = window.getSelection()
var cursorRange = document.createRange()

var emptyElement = document.createTextNode('\u200B')
element[0].appendChild(emptyElement)

cursorRange.setStartAfter(emptyElement)

selection.removeAllRanges()
selection.addRange(cursorRange) 

Upvotes: 8

Views: 3073

Answers (1)

Tim Down
Tim Down

Reputation: 324607

The problem is that WebKit has fixed ideas about where the caret (or a selection boundary) can go and is selecting an amended version of your range when you call the selection's addRange() method. I've written about this a few times on Stack Overflow; here are a couple of examples:

Upvotes: 3

Related Questions