views:

6772

answers:

4

Is it possible to detect, using JavaScript, when the user changes the zoom in a page? I simply want to catch a "zoom" event and respond to it (similar to window.onresize event).

Thanks.

+1  A: 

Check out this jQuery plugin and the corresponding demo. If you're not using jQuery, you could still look at the plugin's source code to get an idea of how to do it.

It appears to watch for the ctrl-wheel/ctrl+/ctrl- commands common to zooming across browsers.

Michael Haren
This method seems to have several flaws. I can't get it to work at all on any of my browsers running off OSX.
Ian Elliott
Chrome doesn't see the events either, seems like the plugin doesn't handle webkit.
Sam Hasler
+5  A: 

There's no way to actively detect if there's a zoom. I found a good entry here on how you can attempt to implement it.

I’ve found two ways of detecting the zoom level. One way to detect zoom level changes relies on the fact that percentage values are not zoomed. A percentage value is relative to the viewport width, and thus unaffected by page zoom. If you insert two elements, one with a position in percentages, and one with the same position in pixels, they’ll move apart when the page is zoomed. Find the ratio between the positions of both elements and you’ve got the zoom level. See test case. http://novemberborn.net/javascript/page-zoom-ff3

You could also do it using the tools of the above post. The problem is you're more or less making educated guesses on whether or not the page has zoomed. This will work better in some browsers than other.

There's no way to tell if the page is zoomed if they load your page while zoomed.

Ian Elliott
+1  A: 

I wrote a little script using flash to detect the current state of the browser zoom and also will call a function if the zoom changes. Maybe this helps you: detect browser zoom for all browsers

best regards, sebastian

sebastian
A: 

I'm using this piece of JavaScript to react to Zoom "events".
It polls the window width. (As somewhat suggested on this page (which Ian Elliott linked to): http://novemberborn.net/javascript/page-zoom-ff3 )

Tested with Chrome, Firefox 3.6 and Opera, not IE.

Regards, Magnus

var zoomListeners = [];

(function(){
  // Poll the pixel width of the window; invoke zoom listeners
  // if the width has been changed.
  var lastWidth = 0;
  function pollZoomFireEvent() {
    var widthNow = jQuery(window).width();
    if (lastWidth == widthNow) return;
    lastWidth = widthNow;
    // Length changed, user must have zoomed, invoke listeners.
    for (i = zoomListeners.length - 1; i >= 0; --i) {
      zoomListeners[i]();
    }
  }
  setInterval(pollZoomFireEvent, 100);
})();
LeoMaheo