0

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 under cursor using JavaScript?
jsfiddle

html:
<p>Each word will be wrapped in a span.</p>
<p>A second paragraph here.</p>

Word: <span id="word"></span>


js:
// wrap words in spans
$('p').each(function() {
var $this = $(this);
$this.html($this.text().replace(/\b(\w+)\b/g, "<span>$1</span>"));
});

// bind to each span
$('p span').hover(
function() { $('#word').text($(this).css('background-color','#ffff66').text()); },
function() { $('#word').text(''); $(this).css('background-color',''); }
);

but i am a very beginner in JavaScript and i am not able to rewrite it to my needs. I do not need to automatically set spans, I will do it manually.

For example I have this:

<span id="sho">しょ</span><span id="ha">は</span><span id="n">ん</span>

When the mouse hovers over one of these characters I want to display a translation of it at a fixed position on the page:

しょ = "sho"  
は = "ha" or particle "wa"  
ん = "n"  
(one at a time)
Community
  • 1
  • 1
Koyagi
  • 143
  • 6

2 Answers2

1

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>
Erik Inkapööl
  • 378
  • 2
  • 11
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>
BCDeWitt
  • 4,540
  • 2
  • 21
  • 34