Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: get input selection range

Tags:

jquery

Is there any event in jQuery to listen to input selections?

For example, let's say I've written foo_bar in a text input. I then select the word foo with the mouse. So the event should return 0, 2 (the string position of foo).

Is there any possible way to accomplish this? I don't know where to start, I'm flipping trought jQuery API pages but can't seems to find anything helpfull.

I though about listening to mousedown events on the input, then somehow retrieve the position of the string where the click happened (not sure if it's even possible) and then getting the position where the mouseup happened.

Any info, sources or examples will be welcomed.

like image 256
jviotti Avatar asked Dec 13 '12 07:12

jviotti


1 Answers

Edit:

$('#foo').select(function(e) {
    var start = e.target.selectionStart;
    var end = e.target.selectionEnd;
    console.log('Changed: ' + start + ' to ' + end);
});

Demo: http://jsfiddle.net/ZyDjV/1/


You can use the select event for this:

$('#foo').select(function(e) {
   console.log('Selection Changed');
});

Demo: http://jsfiddle.net/ZyDjV/

like image 194
techfoobar Avatar answered Sep 20 '22 16:09

techfoobar