0

So I have a textarea in my html called code. Here is my sample:

document.getElementById("code").addEventListener("input", function(ev) {
  console.log(this.selectionStart),
  console.log(this.selectionEnd),
  console.log(ev.data)
})
<textarea id="code"></textarea>

When I've selected the whole text like this:

enter image description here

And I type a - I get:

1
1
a

Instead of like:

1
9
a

I believe this is because it's first deleting the selected text and after that sending the input event on a blank textbox - any ideas how to get around this?

I'm trying to detect changes into the input so I can submit them to my server since I'm trying to implement live code sharing capability.

Dale K
  • 25,246
  • 15
  • 42
  • 71
AnArrayOfFunctions
  • 3,452
  • 2
  • 29
  • 66

1 Answers1

1

You could implement something like:

var oldSelection = {start: 0, end: 0};

with(document.getElementById("code")) {
  addEventListener('mouseup', function(ev) {
    oldSelection.start = this.selectionStart; 
    oldSelection.end = this.selectionEnd;
    console.log(oldSelection);
  })
  addEventListener("input", function(ev) {
    console.log(oldSelection); console.log(ev.data);
  })
}
<textarea id="code"></textarea>

This way when input event occurs you know which range was selected before.

Footnote: you should implement it in a plugin's way so you can attach this behaviour to more than one input.

Cristian Torres
  • 256
  • 3
  • 12