Saturday, May 11, 2019

Footnotes with Plain Javascript

An example of footnotes using plain Javascript, the HTML snippet to consider is:

<p>
Lets see who believes this footnote will work.<a onClick="footnoteOnClickHandler(event)"
 class="fn" href="#">1</a><span class="footnoteBody">This is test text.</span>
I hope it works well.
</p>

The handler for footnotes are given by the Javascript code:

function footnoteOnClickHandler(event) {
    event.preventDefault();
    var elt = event.target;
    if(elt.classList.contains("expanded")) {
        elt.classList.remove("expanded");
        var fnNumber = elt.getAttribute('data-number');
        elt.innerHTML = fnNumber;
    } else {
        elt.classList.add("expanded");
        var fnNumber = elt.innerHTML;
        elt.setAttribute('data-number', fnNumber);
        elt.innerHTML = "x";
    }
};

The CSS is:

.footnoteBody {
    color: #6d6f71;
    display: none;
    font-family: DecimaMono, Consolas, Monaco, monospace;
    font-size: 14px;
    margin: 1em auto;
}
.fn {
    font-size: smaller;
    vertical-align: super;
}
.fn:not(.expanded) + .footnoteBody {
    display: none;
}
.fn.expanded + .footnoteBody {
    display: block;
}

I've tried using plain CSS to handle footnote expandos, but this doesn't work well if I embed a link in the footnote text. For multiple paragraphs, there is a caveat (with both approaches) that I cannot use the <p> tag, but must instead use two consecutive linebreaks <br /><br />. Lets see if this works.1 Footnote fun! I think it works fine.

No comments:

Post a Comment