Caret movement between two adjacent editable elements.

Shows inconsistency between Firefox and Chrome.

by lddubeau

HTML

<p contenteditable="true"><span>foo</span><b>bar</b>

</p>
<button id="move">Move</button>
<button id="location">Location</button>

JavaScript

//
// The inconsistency is when moving the caret between the words "foo"
// and "bar".
// 
// Firefox 20:
// - Moving from the left, the caret will eventually be at the end of
//   the "foo" text node, then will jump over to offset 1 of the "bar"
//   text node.
// - Moving from the right, the caret will eventually be at index 0 of //   the "bar" text node, then will jump to offset length - 1 of the 
//   "bar" text node.
// - Programmatically moving using the "Move" button will put the
//   caret at offset 0 of "bar".
//
// Chrome 26:
// - The caret will never be at offset 0 of "bar", even if set
//   programatically. 
//

$(function () {
    $("#move").click(function () {
        var sel = document.getSelection();
        sel.removeAllRanges();
        var r = document.createRange();
        r.setStart($("b").get(0).childNodes[0], 0);
        sel.addRange(r);
        return false;
    });

    $("#location").click(function () {
        var r = document.getSelection().getRangeAt(0);
        $("body").append("<p>startNode: " + r.startContainer.nodeValue + " offset: " + r.startOffset + "</p>");
    });

    $("#move, #location").mousedown(false);
    $("#move, #location").mouseup(false);

});