0

What's difference between jQuery keypress and JavaScript onkeypress?

When I'm trying to get cursor's start/end position in textbox/textarea in jquery I must use this one (using caret plugin)

$("#sometextbox").keypress(function(e){
   var stratposition = this.caret().start;
   var endposition= this.caret().end;
});

but when onkeypress

<textarea onkeypress="return makeGeo(this,event);"></textarea>

function makeGeo(ob,e) {
    var startPos = ob.selectionStart;
    var endPos = ob.selectionEnd;

}

Is there any way to get cursor's positions in jquery without caret plugin?

worldofjr
  • 3,868
  • 8
  • 37
  • 49
Jaztingo
  • 570
  • 1
  • 5
  • 15

1 Answers1

0

In the jQuery event handler, simply use this.selectionStart and this.selectionEnd:

$("#sometextbox").keypress(function(e) {
  var startPos = this.selectionStart;
  var endPos = this.selectionEnd;
  console.log(startPos, endPos);
}).focus();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<textarea id="sometextbox"></textarea>
Rick Hitchcock
  • 35,202
  • 5
  • 48
  • 79