1

In javascript, the event order is like this:

  1. keydown
  2. keypress
  3. change
  4. keyup

I get the current cursor position with this:

function getCursorPosition(event) {
  var lines = event.target.value.slice(0, event.target.selectionStart)
  return {
    row: lines.length,
    col: lines[lines.length - 1].length
  }
}

If I put the function in onkeydown or onkeypress event, the return value is the cursor position before text inserted

If I put the function in onchange event, the function is not called when I hit arrow key or other key that triggers cursor movement.

If I put the function in onkeyup event, the function is not called when I don't release key (holding keydown).

Now, the only way I can think of is to put the function in both onchange and onkeyup. Flag change event in onchange. Calls the function only if change flag is not true on keyup. And set change flag on keyup to false.

Is there any better way?

Mas Bagol
  • 4,377
  • 10
  • 44
  • 72
  • Possible duplicate of [Get cursor position (in characters) within a text Input field](http://stackoverflow.com/questions/2897155/get-cursor-position-in-characters-within-a-text-input-field) – G07cha Sep 06 '16 at 11:56
  • @KonstantinAzizov the answer there will give different return value on `keydown` and `change` event. I want to track down the cursor position on every keydown, but I need the return value from `keyup` or `change` event. – Mas Bagol Sep 06 '16 at 12:00
  • The `event` object for events that you're using doesn't return current position, also, besides of left/right keys, Ctrl(Command)/Alt jumps there is also mouse pointing so the best option will be to query every time for target element. – G07cha Sep 06 '16 at 12:08
  • _“the function is not called when I don't release key (holding keydown)”_ – and why/how is that a problem? Doing anything with the “current” cursor position while the user is still pressing arrow keys doesn’t seem to make much sense to me. – CBroe Sep 06 '16 at 12:08
  • @CBroe I need to draw cursor somewhere else with the exact same position with the current cursor position even when I holding the key down. So, If I hold left key, the cursor should run to the left too in that place, but with the position after text inseted. It's text editor with hidden textarea. Like codemirror – Mas Bagol Sep 06 '16 at 12:12
  • @KonstantinAzizov That's my question, that `every time`. Is it every `keydown`, every `keypress`, every `change` or every `keyup`? And yes, I mean `event.target` there. I forgot it, sorry. It's typo. – Mas Bagol Sep 06 '16 at 12:16

0 Answers0