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

88
Views
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 answers
Answer question

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 Report

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 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!