Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get hovered word from hover() in Jquery?

I want to make an auto translate from the word that I mouse over 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 the whole text within the paragraph, however, I just want a word that I hover not the whole text. Is there any function in Jquery I can use to archive this? thanks.

like image 985
Houy Narun Avatar asked Oct 15 '25 07:10

Houy Narun


1 Answers

I would do in a different way. I would wrap all the 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>

And I won't use the hover function. It is unreliable and deprecated.

like image 106
Praveen Kumar Purushothaman Avatar answered Oct 17 '25 09:10

Praveen Kumar Purushothaman