Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 is 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) 
like image 383
Mario Uher Avatar asked Oct 10 '13 16:10

Mario Uher


Video Answer


1 Answers

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:

  • Set cursor after span element inside contenteditable div
  • How to set caret/cursor position in a contenteditable div between two divs.
like image 175
Tim Down Avatar answered Oct 05 '22 02:10

Tim Down