Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

127
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda