How to Display Footnotes as Tooltips on Mouse Hover in JavaScript
Showcase
This is a sample sentence. 1
When you hover over the small 1, a tooltip appears saying ‘This is the content of the first footnote.’.
Code
Markdown
이것은 예시 문장입니다. [^1]
[^1]: 이것은 첫 번째 각주 내용입니다.
The medium used to write footnotes does not matter; they even work if written in Markdown instead of HTML.
JavaScript
<script>
document.addEventListener("DOMContentLoaded", function () {
const footnoteRefs = document.querySelectorAll(".footnote-ref");
const footnotes = document.querySelectorAll(".footnotes li");
const footnoteMap = {};
footnotes.forEach(fn => {
const id = fn.id;
const content = fn.innerText.replace("↩", "").trim();
footnoteMap[id] = content;
});
const tooltip = document.createElement("div");
tooltip.className = "footnote-preview";
document.body.appendChild(tooltip);
footnoteRefs.forEach(ref => {
ref.addEventListener("mouseenter", function (e) {
const href = ref.getAttribute("href").replace("#", "");
const preview = footnoteMap[href];
if (preview) {
tooltip.innerText = preview;
tooltip.style.display = "block";
tooltip.style.left = e.pageX + 10 + "px";
tooltip.style.top = e.pageY + 10 + "px";
}
});
ref.addEventListener("mousemove", function (e) {
tooltip.style.left = e.pageX + 10 + "px";
tooltip.style.top = e.pageY + 10 + "px";
});
ref.addEventListener("mouseleave", function () {
tooltip.style.display = "none";
});
});
});
</script>
This implementation is fundamentally a method in JavaScript for ‘generating’ tooltips. Even if the tooltip content is not deliberately prepared in every document, it reads the content corresponding to the footnote, filters out useless parts, and generates it as a web element.
const content = fn.innerText.replace("↩", "").trim();: This is part of the process of removing the extraneous ‘↩’ from the footnote.const tooltip = document.createElement("div");: This is part of the process of creating the tooltip.
CSS
<style>
.footnote-preview {
position: absolute;
}
</style>
Putting aside other styling details, position: absolute; is essential. Adjusting the background color and z-index so that it appears above other elements is left to the implementer.
이것은 첫 번째 각주 내용입니다. ↩︎
