I'm trying to show the user a pop up menu with some options if they highlight any text in the browser. I want the menu to be displayed directly under the highlighted text.
I am currently using getBoundingClientRect() on the range of the text. Passing the object to the menu and using the coordinates to set the positioning.
function doSomethingWithSelectedText() {
let selectedText = getSelectedText();
let sel;
if (selectedText && selectedText.indexOf(' ') === -1) {
console.log('SELECTED TEXT =>', selectedText)
sel = window.getSelection();
if (sel.rangeCount) {
let range = sel.getRangeAt(0);
let coords = range.getBoundingClientRect()
setTimeout(() => { handleShowMenu(coords) }, 800)
}
}
}
const handleShowMenu = (coords) => {
menu.style.display = 'block'
menu.style.left = coords.x + 'px'
menu.style.top = coords.y + 'px'
}
During some highlighting tests of various text elements I notice:
<p> tags perfectly as to my desire.<h3> but closer to the top, almost overlapping the text.<h1> but now partially overlapping the bottom of the text.Any reason for this behavior, as well as a possible solution? thanks.
menu.style.top = coords.y + 'px'
to
menu.style.top = coords.bottom + "px";
Should work if I am understanding your question correctly. You can use single quotes obviously if you prefer, I just prefer double quotes, and I would recommend adding in the semicolons you aren't including but again up to you on that I suppose.