I have a situation that when I click on a button, I need the current selection before the click. Example code goes like
$('div#test').on('click', 'span', function () {
sel = window.getSelection();
$('div#out p').text(sel.toString());
});
The expected behavior is shown here - http://jsfiddle.net/yvondtm/NH2DW/
Things goes right when the image button is clicked. If you make a selection before clicking the image, then you get the output - here it's just a copy of your selection.
But if you click on a text button, the selection gets lost, and the result isn't as expected. It seems like clicking on the text will move the cursor and hence change the selection.
I have checked CSS solutions like this one to disable the selection, as I have put in the fiddle, -webkit-user-select: none;
. It does what it says, but doesn't make any help - even though "range" selection is not allowed, the caret still moves!
How can I solve this problem? Do I have to find some way to convert the text button to as if it were an image?
(No problem to use either js or jquery or css to achieve that. )
The problem here is that the mousedown event that precedes the click event clears any existing selection - after which point window.getSelection()
returns empty. To counter this, simply disable text-selection on the clickable <span>
, in your case #sp
#sp {
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
Demo: http://jsfiddle.net/NH2DW/3/
A round about way that'll ensure the selection stays even if the user accidentally drags his mouse a little after pressing down on the span. Involves JavaScript but.
$('div#di').on('click', 'span', function () {
$('div#out p').text(selection);
});
var selection = '', onSelect = function(_event) {
if($(_event.target).is(':not(div#di span)'))
selection = window.getSelection().toString();
else return false;
};
$(document).mouseup(onSelect).keyup(onSelect).mousedown(onSelect);
Demo: http://jsfiddle.net/NH2DW/7/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With