I'm looking for a simple function (javascript / jquery) that checks whether or not ANY contents of a textarea is selected or highlighted... the function needs to return true or false.
Thanks :)
getSelection() method returns a Selection object representing the range of text selected by the user or the current position of the caret.
You can be sure that no Selectable is selected (which includes InputFields) by simply checking this bool: Code (CSharp): EventSystem. current.
getSelection() Method in JavaScript. The window. getSelection() method in JavaScript allows us to get the text highlighted or selected by the user on the screen. This method returns an object that contains information related to the text highlighted on the screen.
Try this
function isTextSelected(input){
var startPos = input.selectionStart;
var endPos = input.selectionEnd;
var doc = document.selection;
if(doc && doc.createRange().text.length != 0){
return true;
}else if (!doc && input.value.substring(startPos,endPos).length != 0){
return true;
}
return false;
}
Usage
if(isTextSelected($('#textareaId')[0])){
//text selected
}
Demo
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