Skip to content

Instantly share code, notes, and snippets.

@0xemc
Last active April 21, 2021 06:20
Show Gist options
  • Select an option

  • Save 0xemc/b47bd3639cc1db2223640dfcaa27642e to your computer and use it in GitHub Desktop.

Select an option

Save 0xemc/b47bd3639cc1db2223640dfcaa27642e to your computer and use it in GitHub Desktop.
/**
* Container Queries
* this utility provides container query functionality and
* was copied from Phillip Walton's excellent blog post:
* https://philipwalton.com/articles/responsive-components-a-solution-to-the-container-queries-problem/
*/
(function (NAMESPACE, $) {
"use strict";
NAMESPACE.util = NAMESPACE.util || {};
/**
* Enable container queries
*
* @namespace containerQueries
* @version 1.0.0
* @author Michael Collins (hello@mcoll.net)
*/
NAMESPACE.util.containerQueries = (function () {
var init;
init = function () {
// Only run if ResizeObserver is supported.
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);
}
}
};
return {
init: init,
};
})();
})(NAMESPACE, jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment