I am creating a sort of custom bookmarks feature which inserts the highlighted text into an ACF textarea field on a form once the modal button is clicked. This works, but the problem is the function seems to look in the whole document/window and is still running after, so clicking anywhere else gets rid of the inserted text. (Or if I highlight something else within the modal for example it pastes that instead). Please check this short 15 secs video to see what I mean:
https://www.youtube.com/watch?v=uAVQoTuMsCA
And this is the code I'm using:
I have that chapter variable at the top and I tried replacing window/document with chapter but I just get the following error in the console: Uncaught TypeError: Cannot read properties of null (reading 'getSelection') at HTMLDivElement.getSelectedText
Does anyone know how I can get this to only work on the area where the highlighted text is (#chapter) and not have it still happening after the text is inserted?
It was suggested to me to remove the event listener when the modal is open but I don't think I'm doing that right or the function itself is wrong.
Appreciate any help anyone can provide. Thanks.