How can I get, for a HTML TextArea element, get called back on all selection changes to the text edited therein?
(I am currently using the hack of combining keyup, keypress, and mousemove (for dragging selection endpoint), and maybe more could be added, but this is not exactly elegant.)
Can't find it in HTML docs or on SO.
EDIT: By 'all selection changes' I mean including the continuous change during selecting using the mouse, and also I'd like to get a callback when selection collapses and when there is only a caret that is moved (selection is zero length, but changes). I think there is no other way than to implement this by combining many events. Or even using an interval callback and simply comparing, but is also not really good.
What you want is the global selectionchange
event available on the window
or document
. Read about it here.
Add a unique id to your textarea:
<textarea id="unique-id"></textarea>
Add an event listener to the document:
function handleSelection() {
const activeElement = document.activeElement
// make sure this is your textarea
if (activeElement && activeElement.id === 'unique-id') {
const range = {
start: activeElement.selectionStart,
end: activeElement.selectionEnd
}
// do something with your range
}
}
document.addEventListener('selectionchange', handleSelection)
That will run whatever code is in the handleSelection
function.
You can use the onselect
event
object.addEventListener("select", myScript);
https://www.w3schools.com/jsref/event_onselect.asp
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