Create a gist now

Instantly share code, notes, and snippets.

@martynchamberlin /site.js Secret
Last active Nov 14, 2017

What would you like to do?
The JavaScript for DrinkingCaffeine.com
(() => {
if (localStorage.getItem('theme') !== 'dark') {
require('./prism');
}
const config = {
site: 'https://www.drinkingcaffeine.com'
};
/**
* Handle the theme options
*/
const theme = localStorage.getItem('theme');
const select = document.getElementsByTagName('select').theme;
if (select) {
select.value = theme;
select.addEventListener('change', (e) => {
document.body.classList = e.target.value;
localStorage.setItem('theme', e.target.value);
});
}
/**
* @param {element} e The element that was clicked
* @return {element} The element that is being pointed to
*/
const goTo = (e) => {
let goTo = e.getAttribute('href');
// remove the pound sign
goTo = goTo.substr(1);
return document.getElementById(goTo);
};
/**
* The amount of top padding when scrolling to/from a footnote
*/
const padding = 8;
const getDomOffset = () => document.documentElement.scrollTop || document.body.scrollTop;
const setDomOffset = (num) => document.documentElement.scrollTop = document.body.scrollTop = num;
[...document.getElementsByClassName('footnote-ref')].forEach((elem) => {
elem.getElementsByTagName('a')[0].addEventListener('click', (e) => {
setDomOffset(getDomOffset() + goTo(e.target).getBoundingClientRect().top - padding);
e.preventDefault();
});
});
[...document.getElementsByClassName('footnote-return')].forEach((elem) => {
elem.addEventListener('click', (e) => {
setDomOffset(getDomOffset() + goTo(e.target).parentElement.getBoundingClientRect().top - padding)
e.preventDefault();
});
});
/**
* Site search on the archives to search Google properly
*/
const searchForm = document.getElementsByClassName('site-search')[0];
if (searchForm) {
searchForm.addEventListener('submit', (e) => {
searchForm.getElementsByTagName('input').q.value =
`${document.getElementById('search-box').value} site:${config.site}`;
});
}
/**
* Mobile dropdown menu
*/
const menu = document.getElementsByClassName('hamburger')[0];
menu.addEventListener('click', () => {
if (document.documentElement.classList.contains('nav-open')) {
document.documentElement.classList.remove('nav-open');
} else {
document.documentElement.classList.add('nav-open');
}
});
const generateEmail = () => {
const firstHalf = 'comments@drinki';
const secondHalf = 'ngcaffeine.com';
return firstHalf + secondHalf;
}
const email = document.getElementsByClassName('email')[0];
if (email) {
document.getElementsByClassName('email')[0].innerHTML = `<a href="mailto:${generateEmail()}">${generateEmail()}</a>`;
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment