Skip to content

Instantly share code, notes, and snippets.

@sunnymui
Created May 16, 2020 09:09
Show Gist options
  • Save sunnymui/10600aaad3540ac5179931e92bd1244b to your computer and use it in GitHub Desktop.
Save sunnymui/10600aaad3540ac5179931e92bd1244b to your computer and use it in GitHub Desktop.
Resize Observer as JS Media Query Alternative Example
// when you need to listen to the windowish's size to replicate media query behavior, but want
// to use the latest web api's for performance. maye you don't have access to csss for some reason?
// instantiate resize observer with callback to run through elements found
const myObserver = new ResizeObserver(entries => {
entries.forEach(entry => {
// if width larger than 667px (iphone 7 width) that means we're on desktop
if (entry.contentRect.width >= 667) {
console.log('desktop size')
}
console.log('width', entry.contentRect.width);
});
});
// observe the body element for changes
myObserver.observe(document.body);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment