I'm using the new Firepad realtime text collaboration service.
I would like to use the JavaScript getSelection
method on text in the box that the user selects.
However, my code isn't working for whatever reason.
My JavaScript:
function myFunction()
{
alert(window.getSelection());
}
HTML:
<button onclick="myFunction();">Get Selected Text in Firepad</button>
After looking at the plug-in it seems FirePad is using a textarea
.
According to another SO post's answer it seems that textareas
don't use the same selection ranges as other nodes.
The accepted answer explains it like this:
There is extra bizarreness going on with textarea nodes. If I remember correctly they behave as any other nodes when you select them in IE, but in other browsers they have an independent selection range which is exposed via the .selectionEnd and .selectionStart properties on the node.
The highest voted answer shows a solution.
The solution uses the reference to the textarea
node directly and gets the selected range from there using the element's selectionEnd
and selectionStart
properties, similar to this:
function myFunction() {
var e = document.getElementById('thearea');
//Mozilla and DOM 3.0
if ('selectionStart' in e) {
var l = e.selectionEnd - e.selectionStart;
var start = e.selectionStart,
end = e.selectionEnd,
length = l,
text = e.value.substr(e.selectionStart, l);
alert(text);
}
}
DEMO - Using selectionStart
and selectionEnd
for textarea
I'm not sure if this is the same across all browsers these days but the above code and the additional information in the linked SO should hopefully help you in getting the desired result.