Positioning options menu directly under highlighted text

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:

  • The menu is positioned right under the <p> tags perfectly as to my desire.
  • The menu is positioned under the <h3> but closer to the top, almost overlapping the text.
  • The menu is positioned right under the <h1> but now partially overlapping the bottom of the text.

Any reason for this behavior, as well as a possible solution? thanks.