Created
May 16, 2020 09:09
-
-
Save sunnymui/10600aaad3540ac5179931e92bd1244b to your computer and use it in GitHub Desktop.
Resize Observer as JS Media Query Alternative Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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