Skip to content

Instantly share code, notes, and snippets.

@mariocesar
Created December 16, 2019 18:13
Show Gist options
  • Save mariocesar/44a85d5933bb16224cadcd38bab08113 to your computer and use it in GitHub Desktop.
Save mariocesar/44a85d5933bb16224cadcd38bab08113 to your computer and use it in GitHub Desktop.
Add responsive classes to the body using efficient mediaqueries. Useful to integrate CSS/JS actions
(() => {
const checkMediaQuery = (mq) => {
// Check if we add or remove the class depending if it matches or not
if (mq.matches) {
document.body.classList.add('sm')
} else {
document.body.classList.remove('sm')
}
}
// Change the media query and class name for your needs
const mq = window.matchMedia('(max-width: 768px)')
checkMediaQuery(mq) // Trigger for the first time
mq.addEventListener("change", checkMediaQuery) // Call check every time it changes
})()
// This reads as: Run every time a link in the TOC div is click just when the body has the .sm class.
$.on("click", "body.sm #toc a", (button, event) => {
// Hide TOC navigation when clicking, just on SM size
document.getElementById("toc").classList.add("hidden")
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment