Contenteditable: move the cursor outside the inserted html node (webkit / ie)

When I insert the html tag inside the div containing the content, I need the cursor to move outside the (right) of the newly inserted element, so if I continue to print, the new text will be unformatted.

In Firefox, I found this solution to work fine:

node = document.createElement("strong"); node.innerHTML = "test"; range.deleteContents(); range.insertNode(node); range.collapse(false); 

The range of variables is set as follows:

 if (window.getSelection) { var sel = window.getSelection(); if (sel.getRangeAt && sel.rangeCount) { range = sel.getRangeAt(0); } } 

Using the above code in webkit browsers (Chrome / Safari) places the cursor outside the new tag, but to the left.

Is there a solution for this (Chrome / Safari) and for IE support (mostly 9, optionally 8)?

thanks

===============================================

Thanks to Tim for his advice, here's the working code:

 var node = document.createElement("strong"); node.innerHTML = "test"; var space = document.createElement("span"); space.innerHTML = "\u200B"; range.insertNode(space); range.insertNode(node); range.collapse(false); var sel = window.getSelection(); sel.removeAllRanges(); sel.addRange(range); 
+4
source share
1 answer

You need to re-select the range in browsers other than Mozilla. This will work in all major browsers except IE <= 8:

 var sel = window.getSelection(); sel.removeAllRanges(); sel.addRange(range); 

For IE <= 8, you can use a different approach. Here is another answer of mine with a complete example:

fooobar.com/questions/184130 / ...

+5
source

All Articles