0

If I have a div with multiple elements, is there a way for a click mouse event to give me the index at which the click ocured in that element ? JsFiddle

mainDiv.addEventListener('click', (e)=>{
  console.log(e.target)
  // Exact index of the click ?
})
#mainDiv{
  height: 300px;
  width: 300px;
  background: #1f2227;
  color: white;
  white-space: pre-wrap;
}

body{
  margin: 0;
}
<div id='mainDiv'>
   <span>Some Text</span>
   <span>Some Other Text</span>
   <span>More text here</span>
</div>

My first though was to use the coordinates of the click event clientX:, clientY: and check what element is at that spot on the page, but I'm still not sure how to get the exact location in that element.

The event.target already gives me the clicked element, can I the exact position in the element too somehow ?

Some text in a span in a div
   ^ Click occurs there
e.target give me the element clicked, can I get the index ?
Like click occurred on span element at index 3 ?  

The only way I can think of is to use the coordinates of the event, but maybe there's some other way.

RDU
  • 812
  • 1
  • 9
  • 22
  • The easiest way would be to just wrap every character in a tag – Roberto Zvjerković Aug 22 '21 at 12:05
  • check this out https://stackoverflow.com/questions/7457577/onclick-index-in-string but using Jquery solution – Aravind.HU Aug 22 '21 at 12:06
  • @idmean Wrapping every letter would work, but the text already gets parsed and get's surrounded by HTML for highlighting and stuff like that, on a long text that's that's a lot of element that need to constantly be parsed. – RDU Aug 22 '21 at 12:09
  • 1
    @RDU Have you really looked at the answers? Several answers there highlight how to do this without spans. – idmean Aug 22 '21 at 12:11
  • @idmean Yup i found it, looks like using `getSelection()` and `getRangeAt()` is the way to go, thank you. – RDU Aug 22 '21 at 12:13

0 Answers0