Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Checks if window has been zoomed.
// modified from https://stackoverflow.com/a/52008131/1461204
const zoomEvent = new Event('zoom')
let currentRatio = window.devicePixelRatio
function checkZooming() {
if (currentRatio !== window.devicePixelRatio) {
window.dispatchEvent(zoomEvent)
}
}
window.addEventListener('resize', checkZooming)
// usage
window.addEventListener('zoom', () => {
console.log('zoomed!')
})
@alexbfree

This comment has been minimized.

Copy link

alexbfree commented Nov 14, 2019

This is fantastic, but have you any idea how it could be adapted to also detect a 'zoom reset' event (Ctrl+0) ?
It seems like removing the if check at line 6 works, but I suspect this means we are no longer ignoring window resize events. Maybe there is some way to distinguish a resize and a reset...

@souporserious

This comment has been minimized.

Copy link
Owner Author

souporserious commented Nov 14, 2019

Oh, interesting! I never tested that 😅. I'll see if I can come up with anything, thanks for mentioning that! Maybe posting in the StackOverflow link might help give it more exposure.

@megasent1

This comment has been minimized.

Copy link

megasent1 commented Mar 9, 2020

This is fantastic, but have you any idea how it could be adapted to also detect a 'zoom reset' event (Ctrl+0) ?
It seems like removing the if check at line 6 works, but I suspect this means we are no longer ignoring window resize events. Maybe there is some way to distinguish a resize and a reset...

You can do so replacing the currentRatio variable value each time event is triggered:
`const zoomEvent = new Event('zoom')
let currentRatio = window.devicePixelRatio

function checkZooming() {
if (currentRatio !== window.devicePixelRatio) {
currentRatio = window.devicePixelRatio
window.dispatchEvent(zoomEvent)
}
}

window.addEventListener('resize', checkZooming)

// usage
window.addEventListener('zoom', () => {
console.log('zoomed!')
})`

@souporserious

This comment has been minimized.

Copy link
Owner Author

souporserious commented Mar 12, 2020

For anyone that's interested I found out you can use a ResizeObserver and it will update whenever the viewport is zoomed 🎉

@megasent1

This comment has been minimized.

Copy link

megasent1 commented Mar 12, 2020

Be aware that https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserver is not compatible with Safari and IE

@souporserious

This comment has been minimized.

Copy link
Owner Author

souporserious commented Mar 12, 2020

@megasent1 thanks! I should have mentioned that, my bad. Here's a link to a Resize Observer polyfill if anyone needs it. Can confirm it works in Safari.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.