マックス

Japanese Furigana Script

Japanese Furigana Script
Maximilian Boll
Maximilian Boll
13. December 2021

While finalizing the current version of this website using 11ty, I took the time to implement a super small script to help me display furigana for kanji. Furigana are small written hiragana on top of kanji. To keep it clean I only wanted to show the furigana when the respective kanji is hovered. The thought behind is being present with a kanji-only mode at first and only seeing the helping furigana when actually needed, might help while learning the language. I noticed that I'm always reading the furigana instead of the kanji whenever it is present, so I thought hiding it on the first sight would be useful.
Here is an example block of how it looks.

In case you're interested how it works, here is the code. A little description you can find below.

class Furigana {
  constructor(selectors = []) {
      this.selectors = selectors;
      this.regex = /([\u4E00-\u9FAF\u3040-\u3096\u30A1-\u30FA\uFF66-\uFF9D\u31F0-\u31FF]{1})\[(.*?)\]/g;

      this.selectors.forEach(selector => {
          let results = document.querySelectorAll(selector);
          results.forEach(result => {
              result.innerHTML = result.innerHTML.replace(this.regex, "<ruby>$1 <rp>(</rp><rt>$2</rt><rp>)</rp></ruby>");
          });
      });
  }
}

new Furigana(['.content']);

How it works

The class expects an array of element selectors. These DOM elements are then checked for kanji that are followed by brackets [] and this will be replaced by <ruby>Kanji <rp>(</rp><rt>Furigana</rt><rp>)</rp></ruby>. The HTML ruby element suits best for this. Voilá, done.