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

89
Visualizações
Detect which letter from a word is clicked using javascript

I notice different solutions on the internet where is described how to detect the word where the user clicked. But i want to know if there is a solution to detect the letter from a word or the position where the user clicks. Ex:

<div>this is the text</div>

When the user clicks on the first letter in the console should be outputted t.
Is a solution to find the clicked letter like i described above using javascript?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You can probably use the Selection API to check where the cursor is and extract the closest letter to it:

document.onclick = (evt) => {
  const sel = getSelection();
  if (sel.rangeCount) {
    const range = sel.getRangeAt(0);
    const targetedNode = range.startContainer;
    const clickedLetter = targetedNode.textContent.substr(range.startOffset, 1);
    console.log(clickedLetter);
  }
};
<div>this is the text</div>

But it may very well fail in a lot of corner-cases.

about 4 years ago · Juan Pablo Isaza Relatório

0

Use Selection.focusOffset to get position of character which is nearest to cursor click focus.

document.onclick = (event) => {
  const selection = getSelection();
  const charClicked = selection.focusNode.data[selection.focusOffset]
  if (charClicked) {
    console.log(charClicked);
  }
};
<div>this is the text</div>

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