Reputation: 18909
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.
Upvotes: 5
Views: 15163
Reputation: 66663
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/
Upvotes: 8
Reputation: 9370
See this : http://jsfiddle.net/rT5vR/
var getSelected = function(){
var t = '';
if(window.getSelection) {
t = window.getSelection();
} else if(document.getSelection) {
t = document.getSelection();
} else if(document.selection) {
t = document.selection.createRange().text;
}
return t;
}
$("#myElement").select(function(eventObject) {
alert(getSelected().toString());
});
Upvotes: 2