0

If the cursor is positioned somewhere in an input box, is there some way to capture that position using keyup before Firefox moves the cursor to the end of the box?

I'm making a dropdown of suggestions for each input box and I only want the suggestions to be moved into if the cursor was already at the end of the input box. However, when I try to capture the cursor position to test this, it always returns the end, since the cursor moves to the end before my event handler starts.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Chris Middleton
  • 5,654
  • 5
  • 31
  • 68

1 Answers1

0

So I found a solution but it involves a global variable, which seems messy for a little thing like this. I declare a variable

// global scope
var lastCursorPosition;

Then I have a keydown event handler on the inputBox

inputBox.onkeydown = function(event) { 
    if(event.keyCode === 40) { 
        lastCursorPosition = cursorPosition(inputBox); 
    }
};

Finally, in the keyup event (which has other things in it), I do

inputBox.onkeyup = function(event) {
    if(event.keyCode === 40 && lastCursorPosition >= inputBox.value.length - 1) {
        // show suggestions
    }
};

If anyone has a more modular solution, I'd be glad to hear it.

BTW: If anyone's curious, I'm using the cursorPosition function given in this answer.

Community
  • 1
  • 1
Chris Middleton
  • 5,654
  • 5
  • 31
  • 68