Determine the final position of a selection using javascript

I wrote code to detect the end of a selection using javascript and place the marker at the end position. See This jsfiddle: http://jsfiddle.net/vCwwN/

The above code does the following:

  • Handles all LTR scripts correctly (for example, English) (correctly displays the marker at the end).
  • For LTR scenarios (for example, in English), it handles the selection forward (left / top right / bottom) or backward (right / bottom left / top), correctly displaying the marker where the selection is stopped (using the mouse or keyboard).
  • It uses getClientRectsto find all the borders of the selection rectangles and hack to determine the direction of the selection (if backward or not). Depending on the two data, it places the marker at the end.

You can try to choose what is described above for an English script without any problems. The only problem is when you try to process RTL scripts (for example, Arabic), then the marker shows at the beginning of the selected RTL script, and not at the end (where the mouse / keyboard is actually stopped). These problems cause:

  • The initial selection inside the RTL script (Arabic) and the final selection inside the RTL script (Arabic). This shows the marker at the beginning of the selection.
  • The initial selection inside the LTR script (English) and the final selection inside the RTL (Arabic) script. This shows the marker at the beginning of the selection of the RTL script (and not its end).

, (LTR RTL) RTL script . (, LTR RTL LTR, RTL ).

, RTL-, , - . RTL, .

, , RTL script , . , , RTL ( jsfiddle). , :)

+5
1

, .

HTML , Tim Down:

function getSelectionHtml() {
    var html = "";
    if (typeof window.getSelection != "undefined") {
        var sel = window.getSelection();
        if (sel.rangeCount) {
            var container = document.createElement("div");
            for (var i = 0, len = sel.rangeCount; i < len; ++i) {
                container.appendChild(sel.getRangeAt(i).cloneContents());
            }
            html = container.innerHTML;
        }
    } else if (typeof document.selection != "undefined") {
        if (document.selection.type == "Text") {
            html = document.selection.createRange().htmlText;
        }
    }
    return html;
}

, lastCharTRL, , , RTL .

if (lastCharRTL(getSelectionHtml()))
    $('#pointer').css({top: rects[n].top + 10, left: rects[n].left - 10}).show();
else if(backwards)
    $('#pointer').css({top: rects[0].top + 10, left: rects[0].left - 10}).show();
else
    $('#pointer').css({top: rects[n].top + 10, left: rects[n].right}).show();

DEMO

0

All Articles