I'm working with a text area defined as below:
<textarea id="description"></textarea>
I'm trying to detect when some text is selected by the user and the onselect
seems perfect for this. It works perfectly on the w3schools example and I got it working as:
<textarea id="description" onselect="alert('testing');"></textarea>
But when I change this to my own function, nothing happens.
I have tried this using:
document.getElementById("description").addEventListener("onselect", getSelection("description"));
And that executes but on page load and does nothing when I select text.
I've just got simple stuff in the function to try and get it working, I've tested my action selection code and that's fine. I just can't get it to run an onselect event. Here is my testing getSelection
function.
function getSelection(ele)
{
var ele = document.getElementById(ele);
var txt = "Text Selected";
console.log(txt);
}
Any ideas? There seems to be very little information on onselect
with most resources found by people thinking it's for select tags.
You have to pass a reference to the function, right now you just call the function right away using ()
. Also to add the event using addEventListener
you have to use select
instead of onselect
.
document.getElementById("description").addEventListener("select", getSelection);
function getSelection(event)
{
var ele = event.target;
var txt = "Text Selected";
alert(txt);
}
<textarea id="description"></textarea>