1

I tried looking for this on certain posts on this website

but nothing was exactly specified on this topic

(I saw this but it is not what I am looking for Detect which word has been clicked on within a text )

Would anyone know how to check if a word is clicked in just JavaScript?

If it is not possible, let me know and I will mark that on this post.

DerpTrain
  • 69
  • 1
  • 1
  • 3

2 Answers2

1

You could surround every word with a span for example and then attach on-click event on them like this:

let allElems = document.body.querySelectorAll("*:not(.capture-word)");

for (let i = 0, l = allElems.length; i < l; i++) {
  if (allElems[i].offsetParent !== null) {
    let txt = allElems[i].innerText;
    allElems[i].innerHTML = txt.split(' ').map(w => `<span class="capture-word">${w}</span>`).join(' ');
  }
}

let words = document.getElementsByClassName("capture-word");


Array.from(words).forEach(function(element) {
  element.addEventListener('click', () => {
    console.log(element.innerText);
  });
});
<h1> This is an example text here </h1>
<p> It can be in anywhere on the page </p>

If you have any questions about the code, please ask, I will explain.

mdatsev
  • 3,054
  • 13
  • 28
0

Not so much possible as far as I know, unless give the word specific tag and reference it using an eventlistener. Or you probably use window.getSelection but I guess this works mainly for selection, maybe you could be creative with it not too sure on that

And you can try this link suggested in the article you gave

jsfiddle.net/Vap7C/80/

Ezekiel
  • 671
  • 5
  • 13