Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set cursor after span element inside contenteditable div

How can I set the cursor after a span element inside an contenteditable div? Right now, I've an image inside a span element, inside the contenteditable div.

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

like image 534
Laurens Schuitemaker Avatar asked Apr 04 '13 14:04

Laurens Schuitemaker


2 Answers

In browsers other than IE <= 8, this will do it:

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 (notably WebKit-based ones) have fixed ideas about which positions in the document are valid for the caret and will normalize any range you add to the selection to comply with those ideas. The following example will do what you want in Firefox and IE 9 but not in Chrome or Safari as a result:

http://jsfiddle.net/5dxwx/

None of the workarounds are good. Options include:

  • add a zero-width space character after the span and select it
  • use an <a> element instead of a <span> because WebKit makes an exception for <a> elements
like image 61
Tim Down Avatar answered Nov 17 '22 01:11

Tim Down


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

like image 4
Mohit Turkar Avatar answered Nov 17 '22 02:11

Mohit Turkar