0

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.

1 Answers1

2

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

connexo
  • 53,704
  • 14
  • 91
  • 128