0

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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
koMah
  • 429
  • 5
  • 18

1 Answers1

0

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);
});
David Hellsing
  • 106,495
  • 44
  • 176
  • 212
  • Thanks for the setTimeout idea.. You think that this "way" can cause some problems? Like as multi-triggering or something like that? – koMah Dec 15 '12 at 01:01