Created
August 15, 2018 18:24
-
-
Save GrantCuster/702d544161362b4a840a2ae818e0cbb8 to your computer and use it in GitHub Desktop.
Create inline footnotes in markdown files in Gatsby.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Put in gatsby-browser.js | |
exports.onRouteUpdate = ({ location }) => { | |
setTimeout(function() { | |
let og_footnotes = document.querySelector('.footnotes') | |
if (og_footnotes) { | |
let footnotes = document.querySelectorAll('.footnotes ol li') | |
for (let i = 0; i < footnotes.length; i++) { | |
let f_content = footnotes[i] | |
let link = f_content.querySelector('a') | |
let href = link.getAttribute('href') | |
let footnote = document.querySelector(href) | |
let footnote_clone = footnote.cloneNode(true) | |
let footnote_container = document.createElement('span') | |
let footnote_trigger = document.createElement('span') | |
footnote_trigger.className = 'footnote_trigger' | |
footnote_trigger.appendChild(footnote_clone) | |
footnote_container.className = 'footnote_container' | |
let content_div = document.createElement('div') | |
content_div.className = 'footnote_content' | |
content_div.innerHTML = | |
'<span class="footnote_content_number">' + | |
(i + 1) + | |
'.</span>' + | |
' ' + | |
f_content.innerHTML.trim() | |
footnote_container.appendChild(footnote_trigger) | |
footnote_container.appendChild(content_div) | |
footnote.parentNode.replaceChild(footnote_container, footnote) | |
function toggleFootnote(footnote_container, e) { | |
if (footnote_container.classList.contains('active')) { | |
footnote_container.classList.remove('active') | |
} else { | |
footnote_container.classList.add('active') | |
} | |
e.preventDefault() | |
} | |
footnote_trigger.addEventListener( | |
'click', | |
toggleFootnote.bind(this, footnote_container), | |
false | |
) | |
let footnote_backref = footnote_container.querySelector( | |
'.footnote-backref' | |
) | |
footnote_backref.addEventListener( | |
'click', | |
toggleFootnote.bind(this, footnote_container), | |
false | |
) | |
} | |
og_footnotes.remove() | |
} | |
}, 0) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment