5

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.

1
  • @Anujith the link not work (404 Not Found) Commented Dec 3, 2018 at 11:33

2 Answers 2

8

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/

Sign up to request clarification or add additional context in comments.

2 Comments

Is there a way to retrieve the selected text or its positions? I'm inspecting the object it returned but doesn't seems to store anything
Great and very clean. Thanks
2

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());
});

1 Comment

great, It's a cleaner implementation of the code at the webpage you posted. I'll try it now. BTW, how much cross-browser is this?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.