Get hover word from hover () in JQuery?

I want to make an automatic translation from a word that I click on it. I use

$('p').hover(function () {
  var hoveredWord = $(this).text();
  translate(hoveredWord, 'en'); // function to translate a word to English Language
});

      

It will return all the text in the paragraph, however I just need a word that I don't find all the text. Is there some function in JQuery that I can use to archive it? thank.

+3


source to share


1 answer


I would have done otherwise. I would wrap all text content using <span>

:



$(function() {
  $('p').html(function () {
    var cont = [];
    return "<span>" + $(this).text().split(" ").join("</span> <span>") + "</span>";
  }).on("mouseover", "span", function() {
    var hoveredWord = $(this).text();
    console.log(hoveredWord);
    // translate(hoveredWord, 'en'); // function to translate a word to English Language
  });
});
      

span:hover {background: #ccf;}
      

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Hello, World! How are you?</p>
      

Run code


And I will not use the function hover

. This is unreliable and outdated.

+4


source







All Articles