Skip to content

Instantly share code, notes, and snippets.

@c-kick
Last active March 23, 2022 10:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save c-kick/846b9f66307bd1babde426426407ed25 to your computer and use it in GitHub Desktop.
Save c-kick/846b9f66307bd1babde426426407ed25 to your computer and use it in GitHub Desktop.
setBreakpoints - Adds the current breakpoint-name (as specified in the 'breakpoints' const) to the body class and notifies anyone listening of the change via the 'breakPointChanged' event.
/** This script adds the current breakpoint-name (as specified in the 'breakpoints' const)
* to the body class and notifies anyone listening of the change via the 'breakPointChanged' event.
*
* Default breakpoint names and cutoff pixel values taken from Bootstrap 5's default responsive breakpoints:
* https://getbootstrap.com/docs/5.0/layout/breakpoints/
*
* Usage:
* - include the script into your page and the class is updated, and will continue to update whenever
* the width of the window changes enough to trigger another breakpoint.
* - optionally listen for the event via:
* document.addEventListener('breakPointChange', (event) => {
* //do stuff
* });
*/
if (typeof window.matchMedia === 'function') {
function setBreakpoints() {
const breakpoints = [
{name: 'xs', min: 0},
{name: 'sm', min: 576},
{name: 'md', min: 768},
{name: 'lg', min: 992},
{name: 'xl', min: 1200},
{name: 'xxl', min: 1400}
];
let x = breakpoints.length;
while (x--) {
let name = breakpoints[x].name,
pixMin = breakpoints[x].min,
pixMax = breakpoints[x + 1] ? (breakpoints[x + 1].min - 0.02) : 0;
let mediaQuery = '(min-width: ' + pixMin + 'px' + (pixMax ? ') and (max-width: ' + pixMax + 'px' : '') + ')';
window.matchMedia(mediaQuery).addEventListener('change', function (e) {
if (e.matches) {
document.dispatchEvent(new CustomEvent('breakPointChange', {detail: {name}}));
}
document.body.classList.toggle(name, e.matches);
}
);
//run on init (usually window load)
document.body.classList.toggle(name, ((window.innerWidth > pixMin && window.innerWidth < pixMax) || window.innerWidth > pixMin && x === breakpoints.length - 1));
}
}
if (document.readyState === "complete") {
setBreakpoints();
} else {
window.addEventListener("DOMContentLoaded", setBreakpoints);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment