Detect Browser Zoom

There's a propery on the windows object that gives the current zoom level of the browser, window.devicePixelRatio.

When it changes, the window.resize event is triggered:

var zoomLevel = window.devicePixelRatio
window.addEventHandler('resize', function() {
if(zoomLevel !== window.devicePixelRatio) {
zoomLevel = window.devicePixelRatio
// redraw your SVG graphs or whatever
}
})

Update 2020-05-08: As discussed in the article Can JavaScript Detect the Browser’s Zoom Level? on CSS Tricks, devicePixelRatio is not suitable to detect the actual zoom level and even the example above is not working in all modern browsers.

Published: April 7th, 2020
Tags: til,JS