It seems that window.getSelection() is empty until mouseup occurs. I am able to get the clicked word and select it on mouseup, but I need to do this on mousedown (before mouseup occurs). In this jsfiddle example I am triggering mouseup (which is triggered successfully) but the text selection is still empty until the physical mouseup occurs.
$(function() {
app_init();
});
function app_init() {
container = $('div');
selection = false;
word = false;
start = false;
end = false;
if(window.getSelection) {
selection = window.getSelection();
selection.empty();
} else {
alert('Please update your browser to use this application.');
}
container.mousedown(function(e) {
console.log('mousedown');
mouse_press(e);
});
container.mouseup(function(e) {
console.log('mouseup');
mouse_release(e);
});
}
function mouse_press(e) {
$(e.target).trigger('mouseup'); // this triggers the mouseup but selection is empty
}
function mouse_release(e) {
handle_selection(); //physical mouseup works
}
function handle_selection() {
selection = window.getSelection();
//console.log(selection);
if(selection.isCollapsed) {
// this is how i am selecting the clicked word, and yes i know .modify is non-standard
selection.modify('move', 'forward', 'character');
selection.modify('move', 'backward', 'word');
selection.modify('extend', 'forward', 'word');
word = selection.toString();
start = selection.anchorOffset;
end = selection.focusOffset;
console.log( 'word:'+word+' start:'+start+' end:'+end );
}
}
Is there any other way to trigger the text selection (which isCollapsed true) while the mouse is still down?