Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect direction of user selection with javascript

I am emulating text editor in my project with custom caret, but native selection. Is there any way how to detect in which direction did user select the text? Lets say, that user has selected text "hello world". There are two possibilities, he could start with clicking his mouse on letter 'd' and ends on letter 'h', or he could start on letter 'h' and end on letter 'd'. Is there any easy way how to distinguish between these two situations? Thank you.

like image 301
Ondra Avatar asked Feb 07 '12 16:02

Ondra


4 Answers

Old question, but I thought I'd add an easier solution:

var sel = getSelection(),
position = sel.anchorNode.compareDocumentPosition(sel.focusNode),
backward = false;
// position == 0 if nodes are the same
if (!position && sel.anchorOffset > sel.focusOffset || 
  position === Node.DOCUMENT_POSITION_PRECEDING)
  backward = true; 

Node.compareDocumentPosition (MDN)

like image 86
willlma Avatar answered Nov 08 '22 14:11

willlma


As far as I'm aware there is no property or event native to Javascript that will tell you the direction. This site details how to track mouse direction, you can tweak it to your needs.

Essentially, as long as you can retrieve the mouse position (with either loc.pageX or Y, or event.clientX or Y), you may be able write your own functions to track the direction based on position and time.

In your case you'd probably only want to capture this when the user has text 'selected', ie on the mousedown event.

like image 30
Igor Avatar answered Nov 08 '22 14:11

Igor


track the mousedown X offet and then the mouseup X offset, and the result shows the direction: (using jQuery)

var textSelectionDirection = (function(){
    var direction = '', mouseDownOffset = null;

    function getDirection(e){
        if( e.type == 'mousedown' )
            mouseDownOffset = e.clientX;
        else if( e.type == 'mouseup' ){
            direction = e.clientX < mouseDownOffset ? 'left' : 'right';
            console.log(direction);
        }
    }

    return getDirection
})();

$(document).on('mousedown mouseup', textSelectionDirection);

DEMO: http://jsfiddle.net/ffumv/

like image 20
vsync Avatar answered Nov 08 '22 14:11

vsync


This should work:

function isBackwards(sel) {
  var rg = document.createRange();
  rg.setStart(sel.anchorNode, sel.anchorOffset);
  rg.setEnd(sel.focusNode, sel.focusOffset);
  return !rg.toString();
}

Note: If you allow selections of nothing but breaks and whitespace you need to modify above function since it would return true in such a case, no matter what.

like image 31
user1521685 Avatar answered Nov 08 '22 13:11

user1521685