4

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.

Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
Houy Narun
  • 1,557
  • 5
  • 37
  • 86
  • 2
    This may be a bit overkill but you could put each word in the `p` in it's own span, like: `

    The quick fox etc..

    `. Then you can add the `hover` to each to `span`.
    – Halcyon Jul 25 '17 at 13:12
  • in this case you have to wrap your each word inside the span/label tag. so you will be able to perform event on that – RAUSHAN KUMAR Jul 25 '17 at 13:13
  • `hover` is combination of `mouseover` and `mouseout` event in `Jquery` so it wiil return all the paragraph if you mouseover a paragraph – Ghanshyam Singh Jul 25 '17 at 13:14

1 Answers1

5

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.

Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252