Skip to content Skip to sidebar Skip to footer

Get A Word Under Cursor And Output A Corresponding Translation Using JavaScript

I want to implement a kana-helper into my website: When the user hovers over a kana (japanese character) it shall output the right translation. I have found this: How to get a word

Solution 1:

You can just use the ::before pseudo-selector to do it. No JavaScript required.

.kana {
  position: relative;
}
.kana:hover {
  color: blue;
}
.kana:hover::before {
  position: absolute;
  content: attr(romaji);
  top: 1em;
  color: blue;
}
<span class="kana" romaji="sho">しょ</span><span class="kana" romaji="ha"></span><span class="kana" romaji="n"></span>

Solution 2:

I've taken the liberty to use a data-*-attribute as there should not be more than one element with the same id on a page.

// bind to each span
$('#raw span').hover(
    function() { $('#translation').text($(this).css('background-color','#ffff66').data('translation')); },
    function() { $('#translation').text(''); $(this).css('background-color',''); }
);
#translation {
  font-weight: 700;   
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="raw">
  <span data-translation="sho">しょ</span><span data-translation="ha"></span><span data-translation="n"></span>
</div>

Translation: <span id="translation"></span>

Post a Comment for "Get A Word Under Cursor And Output A Corresponding Translation Using JavaScript"