Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

126
Views
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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!