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:
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'sselectionEnd
andselectionStart
properties, similar to this:DEMO - Using
selectionStart
andselectionEnd
fortextarea
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.