I am writing a javascript function that needs to check first whether the user has highlighted / selected some text on the page. I read online that this should work:
if ( typeof window.getSelection() != "undefined" ) {
var x = window.getSelection().toString();
}
else {
//nothing is selected, so use default value
var x = "default value";
}
But that did not work because even when nothing is selected, window.getSelection() returns an object.
if ( typeof window.getSelection().toString() !== "" ) {
var x = window.getSelection().toString();
}
else {
//nothing is selected, so use default value
var x = "default value";
}
But even though window.getSelection().toString() returns an empty string, it still uses that empty string rather than the default value.
Finally, if ( window.getSelection() )
did not work either.
How can I know whether something is selected?
I am writing a javascript function that needs to check first whether the user has highlighted / selected some text on the page. I read online that this should work:
if ( typeof window.getSelection() != "undefined" ) {
var x = window.getSelection().toString();
}
else {
//nothing is selected, so use default value
var x = "default value";
}
But that did not work because even when nothing is selected, window.getSelection() returns an object.
if ( typeof window.getSelection().toString() !== "" ) {
var x = window.getSelection().toString();
}
else {
//nothing is selected, so use default value
var x = "default value";
}
But even though window.getSelection().toString() returns an empty string, it still uses that empty string rather than the default value.
Finally, if ( window.getSelection() )
did not work either.
How can I know whether something is selected?
Share Improve this question asked Jun 10, 2013 at 15:53 Bryan GentryBryan Gentry 8631 gold badge8 silver badges25 bronze badges1 Answer
Reset to default 5This will work: http://jsfiddle/tknkh9xa/1/
(window.getSelection().toString() != "")
Your problem was that you were checking the typeof
on the result of the toString()
... which would not be an empty string (it would be "string").
Also, since an empty string is a falsy value, you could do just
if(window.getSelection().toString())