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.


This article has been published on on my blog. Here's a list of all articles if you're interested in this kind of stuff.

Tags: til,JS