Search code examples
javascriptjqueryselectionjquery-eventsrangy

How to get a selection.range before mousedown event?


I don't understand why I can't get the right range object. It's hard for me to explain the problem.

For example: I have five divs, each div contain a phrase. Logically if I trigger a mousedown event in one of these div I can get the event-target. Ok, this is elementary.

But, if I work with the range object on a mousedown event, the event-target is always that I have clicked but the range.startContainer is pointing at the previous div;

Check out this fiddle:


 1 LineLineLine
 2 LineLineLineLineLine
 3 LineLineLineLine
 4 LineLineLine
 5 LineLineLineLine

Steps for reproducing the problem ( See console ):

  1. Hold down your mouse button on first line ( Console say "undefined" [*] )
  2. Release your mouse button ( Range is securely pointing at first line now )
  3. Hold down your mouse button on the fourth line ( Console say "firstline" )
  4. The console show the previous clicked line

[*] Is undefined because the document don't have a range yet, but this is insignificant because I can create one at fly and inject him in document.

I can deduce that the mousedown event is executed before the range.. Or not?


Solution

  • I don’t think you can get the right range on mousedown, the trigger is faster than the range detection. You can use mouseup (demo):

    $("div.line").mouseup(setPos);
    

    Or add a small delay (demo):

    $("div.line").mousedown(function() {
        setTimeout(setPos, 4);
    });