Asking
Asking

Reputation: 4172

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?

Upvotes: 0

Views: 754

Answers (2)

Rahul Kumar
Rahul Kumar

Reputation: 3157

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>

Upvotes: 3

Kaiido
Kaiido

Reputation: 136638

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.

Upvotes: 3

Related Questions