Skip to content
Advertisement

Vanilla JavaScript: How to dynamically create a button that shows up after user has selected some text and then do something with that text?

I’m working on a little project in which users can upload their .docx files and then read those files (and files from other users) right in the app. For this purpose I have extracted text from docx and displayed it in a div in separate view and html page. Now, I would like to give my users an option to select some text from this div (and only this div) and when they have selected it, I would like to display a button that hovers over that text on which they can click. This button would be for adding selected text to their notes, similar to what MS Edge does automatically when we select some text (it adds those three dots which then open a menu for copying and the rest). Or even more precisely, if you’re familiar with Coursera website – when some text from lessons is selected, a ‘Save Note’ button appears and clicking it adds the selected text right in your notes without the need for users to do anything else, and they can find the saved note whenever they go to their notes (photo bellow shows this button in action).

Coursera ‘Save Note’ button example

However, I’m not sure how to implement this. I think I would use window.getSelection, and then store the selection in some const that I would then send via fetch to my server to add it to the Notes Model (I’m using Django). But I don’t know how to implement this, nor where to even start. How to even make a button hover over other text like this, only when a selection is selected? Any kind of help is much appreciated!! Note: I would like to this in Vanilla JS if possible, since I’m not yet familiar with React or other libraries/frameworks.

Advertisement

Answer

Had to answer my own question, for future references. Thanks to solutions from Tyler Durden and Endoxos, after a few hours playing with it, this is now the code that (for the most part) does what I wanted it to do (it’s also commented out for this answer for easier understanding):

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement