Skip to content

Instantly share code, notes, and snippets.

@chrismademe
Created October 10, 2019 07:59
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 chrismademe/ad5899cf6ec29fa3671e99f3ac734368 to your computer and use it in GitHub Desktop.
Save chrismademe/ad5899cf6ec29fa3671e99f3ac734368 to your computer and use it in GitHub Desktop.
Container Query using ResizeObserver
/**
* Written by Philip Walton
* @see https://philipwalton.com/articles/responsive-components-a-solution-to-the-container-queries-problem/
*/
if ('ResizeObserver' in self) {
// Create a single ResizeObserver instance to handle all
// container elements. The instance is created with a callback,
// which is invoked as soon as an element is observed as well
// as any time that element's size changes.
var ro = new ResizeObserver(function(entries) {
// Default breakpoints that should apply to all observed
// elements that don't define their own custom breakpoints.
var defaultBreakpoints = {SM: 384, MD: 576, LG: 768, XL: 960};
entries.forEach(function(entry) {
// If breakpoints are defined on the observed element,
// use them. Otherwise use the defaults.
var breakpoints = entry.target.dataset.breakpoints ?
JSON.parse(entry.target.dataset.breakpoints) :
defaultBreakpoints;
// Update the matching breakpoints on the observed element.
Object.keys(breakpoints).forEach(function(breakpoint) {
var minWidth = breakpoints[breakpoint];
if (entry.contentRect.width >= minWidth) {
entry.target.classList.add(breakpoint);
} else {
entry.target.classList.remove(breakpoint);
}
});
});
});
// Find all elements with the `data-observe-resizes` attribute
// and start observing them.
var elements = document.querySelectorAll('[data-observe-resizes]');
for (var element, i = 0; element = elements[i]; i++) {
ro.observe(element);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment