Home » vue » Is it possible to fire any function when text selected without mouseup? [duplicate]

Is it possible to fire any function when text selected without mouseup? [duplicate]

Posted by: admin November 26, 2021 Leave a comment

Questions:

I have a content editable div. So I need to call to a function when any text is selected inside of that div. Is it possible to trigger a function when text is selected by mouse and keyboard too.

Answers:

The DOM API has the selectionchange event for that:

https://developer.mozilla.org/en-US/docs/Web/Events/selectionchange

Unfortunately an even listener for that event can only be attached to the document object, and not to any specific element.

So what you can do is attach the listener in the mounted() hook:

mounted() {
   document.addEventListener('selectionchange', this.handleSelectionChange);
}

I’ve created a small sample project showing the usage. Unforunately the event target is always document.

https://codesandbox.io/s/kmxp4roz97