8

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) 
Mario Uher
  • 12,249
  • 4
  • 42
  • 68

1 Answers1

3

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:

Community
  • 1
  • 1
Tim Down
  • 318,141
  • 75
  • 454
  • 536