When you style you components in CSS using media queries it's quite often when for a particular component CSS is just not powerful enough to fulfill you needs. Then you have to use JS for that purpose so you copy your breakpoint and use something like window.addEventListener('resize', ...) and rely on window.outerWidth/innerWidth.
Besides in some cases window.outerWidth/innerWidth can be inconsistent in different browsers (see here) so relying on them is not very safe, adding another addEventListener and "window.innerWidth > 1280" just makes your code less maintainable.
Device Observer allows you to configure your breakpoints once and then write media queries conditions in JS the same way you are used to in CSS
It uses window.matchMedia that always returns correct results.
Supports both mobile and desktop-first approaches (can be configured via options).
Use the package manager npm for installation.
$ npm install @deleteagency/device-observer
const devices = {
'mobile': 0,
'tablet': 768,
'desktop': 1024,
}
const deviceObserver = new DeviceObserver(devices)
deviceObserver.subscribeOnResize(() => {
// this will triggered not more than ones at 50ms by default
console.log('Do some logic on every resize');
});
deviceObserver.subscribeOnChange((newDevice, oldDevice) => {
if (deviceObserver.is('<', 'desktop')) {
console.log('Do some logic for smaller devices');
} else {
console.log('Do some logic for bigger devices');
}
});
Sets options described in Options section
Required
Type: Object
Debounce time in milliseconds for handling window resize event.
Default value - 50
.
Type: number
Whether to use mobileFirst approach in current device determining.
Default value - true
.
Type: Boolean
Subscribe on viewport changing with debounce time. Passed callback function will be called every time viewport is changes
Required
Type: (currentDevice) => void
Subscribe on device change. Passed callback function will be called every time device is changes (in terms of user devices passed as the first argument to deviceObserver.init())
Required
Type: (newDevice, oldDevice) => void
Returns Boolean
Just an alias for the above methods
Required
Type: string
Allowed values: '=', '>', '>=', '<', '<='
Required
Type: string