After clicking on selected text, window selection is not giving updated range
You fiddle is working just fine. But, yes sometimes when you do selections in quick succession, then it fails to register the click.
The problem really lies in the way you have implemented it on click
on the text input
itself. A click event is generated when a mouseup follows a mousedown. A selection happens when you mousedown then drag and then mouseup.
If you separate out the selection retrieval then this problem won't occur.
See this updated fiddle: http://jsfiddle.net/zRr4s/21/
Here, the selection retrieval is donw on a button click, instead of the input itself.
i.e., instead of:
$('#xyz').click(function (e) { ...
using this:
$('#btn').click(function () { ...
where, btn is:
<input id="btn" type="button" value="get selection" />
Hope that helps.
Update:
If you insist on handling event only on the input, then listening mouseup would be better option:
See this fiddle: http://jsfiddle.net/zRr4s/22/
$('#xyz').on("mouseup", function (e) { ...
Update 2:
To handle your requirement of in-context click, you will have to first clear the selection. For this to happen you will have to handle mousedown. So, that will defeat your purpose of having only one handler. Anyway,
You updated fiddle: http://jsfiddle.net/zRr4s/29/
And, this is how you do it:
$('#xyz').on("mousedown", function () {
clearTheSelection();
});
Where clearTheSelection
is another function:
function clearTheSelection() {
if (window.getSelection) {
if (window.getSelection().empty) { // Chrome
window.getSelection().empty();
} else if (window.getSelection().removeAllRanges) { // Firefox
window.getSelection().removeAllRanges();
}
} else if (document.selection) { // IE?
document.selection.empty();
}
}
The complete code for the above function taken from this answer: https://stackoverflow.com/a/3169849/1355315
Hope that completes all your problems.