Set cursor after span element inside contenteditable div

How to set cursor after span element inside contenteditable div? Right now I have an image inside a span element, inside a contenteditable div.

When I add some characters, they are added within the range, but I want them to be added after the span element. Any ideas how I can achieve this?

+8
javascript html contenteditable
source share
4 answers

On browsers other than IE <= 8, this will do the following:

function placeCaretAfterNode(node) { if (typeof window.getSelection != "undefined") { var range = document.createRange(); range.setStartAfter(node); range.collapse(true); var selection = window.getSelection(); selection.removeAllRanges(); selection.addRange(range); } } 

However, some browsers (in particular, WebKit-based) have a fixed view of which positions in the document are valid for the caret, and normalize any range that you add to the selection to fit these ideas. The following example will do what you want in Firefox and IE 9, but not in Chrome or Safari:

http://jsfiddle.net/5dxwx/

None of the workarounds are good. Options include:

  • add a zero space character after the range and select it
  • use the <a> element instead of the <span> because WebKit throws an exception for <a> elements
+17
source share

This function controls what I had in mind:

 <script type="text/javascript"> function pasteHtmlAtCaret(char) { var sel = rangy.getSelection(); var range = sel.rangeCount ? sel.getRangeAt(0) : null; var parent; if (range) { var parentEl = document.createElement("span"); jQuery(parentEl).addClass('char').addClass('latest'); parentEl.appendChild(range.createContextualFragment(char)); // Check if the cursor is at the end of the text in an existing span if (range.endContainer.nodeType == 3 && (parent = range.endContainer.parentNode) && (parent.tagName == "SPAN")) { range.setStartAfter(parent); } range.insertNode(parentEl); if(jQuery(parentEl).parent().get(0).tagName.toLowerCase() == 'span'){ var spanParent = jQuery(parentEl).parent('span'); var parentEl = jQuery('<span class="char latest spanchild"></span>').insertAfter(spanParent).append(parentEl).get(0); } jQuery("span.spanchild").each(function(index, element){ var content = jQuery(element).children('span.char').first().html(); jQuery(element).children('span.char').remove(); jQuery(element).html(content); jQuery(element).removeClass('spanchild'); }); range.setStartAfter(parentEl); rangy.getSelection().setSingleRange(range); jQuery(parentEl).removeClass('latest'); } } </script> 
+2
source share

Just span.contentEditable = false for Tim's solution to work correctly;)

+1
source share

I managed to solve this problem using the 'a' tag with   . Example: - "<a>"+ content/element you want to add +"</a>&nbsp;"

0
source share

All Articles