[Update]: Example ZIP wasn’t working in deed. Thanks Unabus for the hint.
[Update]: jQuery no longer required. Changed initialisation method.
[Update]: Added ActionScript Source.
[Update]: Sorry, i posted the wrong version ( Thanks Ash for the hint ). The latest version now really supports Internet Explorer.

Every modern Web-Browsers gives you the possibility to zoom in/out the content of a website. If you zoom into the website this will easily enlarge the complete content for you. It includes all text and images. In many cases that makes it easier to read website at least for people with poor eyesight.
Now comes the BUT. Sometimes you have strange side-effects. For example when using the Flash plugin. If you don’t allow rescaling the flash content, which the flashplayer would otherwise easily does, you got some ugly sideeffects black borders or whatever. You may have your reasons for having none scalable flash ( if i don’t ran into this problem i would not write this, so at least i had my reasons – not only laziness ).

In many cases the side-effects don’t destroy your complete website and make it unuseable, but i would at least like to give the users a very small hint that their browser is zoomed and that this may effect the website layout ( i just recognize that this reminds a bit at the „This website is optimized for IE 6.0 and 1024×768 pixels“ notices – how i hate this ). If i detect that the browser is zoomed if could also use other versions of my plugins/scripts/css/images/whatever, to make it look nice again – of couse the detection is the first step.

To detect this circumstance i wrote a little JavaScript because i don’t find any standard JavaScript-attribute or method which does this for me. There are also some scripts which attaches resize handler on HTML-elements (http://www.alistapart.com/articles/fontresizing/) , but it only detects the resizing itself and don’t notice when it is already resized or zoomed in this case.

As you maybe know i really love the Flash and JavaScript combination. So what my script does is to create a flash in the background and reads it stage-size (stage.stageHeight). If this differs from the originally setted flash size: et voilà: your client is zoomed (this does not for the iPhone, because there is not flash in safari allowed).

The script inserts a flash at the bottom right corner of the browsers viewport (10px * 10px by default). After the flash is initialised completly if will be moved to bottom left corner that only one pixel is still in the viewport, to be sure that the flash is still handled ( mozilla will not handle flash which is not at least visible in the viewport ).

Everything there is to do for you is to insert three two additional JavaScript files ( if you already use jQuery and swfObject, it’s only one additional ), set some configuration parameters and define your callback method. Just call the init-method and handle the result within the callback method. The init-method will return false if there is no flash are not the required flash is installed on the client. The following example will open an alert window as soon as the user changes the zoom level and when the zoom level is initally not „1“:

<script type="text/javascript" src="../javascript/swfobject.js"></script>
<script type="text/javascript" src="../javascript/swfZoomDetection.js"></script>
<script type="text/javascript">
  swfZoomDetection.init({
     'onZoomChange': function(obj){ alert(obj.scale) },
     'getInitIfOne': true,
     'initCallOnly': false,
     'frameRate': 25
  });
</script>

The configuration parameters are:
onZoomChange: This is the callback function, called when the users changes the zoom level of his browser. This function will also be called after the initialisation if the browser is already zoomed.

getInitIfOne: If the browser is not already zoomed ( zoom level = 1 ) the onZoomChange callback will not called after the initialisation by default. If you set this to true the callback function will also be called at beginning if the browser is not zoomed.

initCallOnly: If this is set to true the flash will be removed from DOM after if detects the first zoom level. After this no further zoom level changes by the user are detected.

frameRate: The flash will check „onEnterFrame“ if the stageHeight and the zoom level has changed. So the more frames there are, the more precise you could check for updates. But i think at least a frameRate of 10 frames per second ( = 10 checks per second ) is more than precise enough.

Some further hints: Be aware you are using this script within a server environment and not from local filesystem, because of the flash player security model. The init-method should be called when the document is completly loaded. So use the $(document).ready() from jQuery, dojo.addOnload() from dojo, or the onLoad handler of the body-element.

  <body onLoad="loadFunction()">
     function loadFunction(){
         swfZoomDetection.init({ .... });
     }
  </body>

Download (2010/11/09): Simple Example (ZIP, 16kB)
Download (2010/08/24): swfZoomDetection (ZIP, 20kB)
Download (2010/02/12): swfZoomDetection AS Source (ZIP)

I hope this helps anybody.

cheers,
Sebastian

58 thoughts on “ How to detect the Browsers Zoom Level / If the user changes Browser Zoom ”

  1. This has been very helpful. Thank you!

    FYI: It seems as though your html example (swfZoomDetection.html) is missing these two tags:
    closing head
    opening body

    BTW, Does this work with IE?

  2. Hi Ash,

    thanks for the hint with the missing tags, and also for the hint with IE. There were in deed problems on the version i posted here. I updated it and now this will also work fine for IE. Nice to see that somebody really used it :)

    cheers,
    Sebastian

  3. Can you provide the source actionscript file? I’d like to make use of this but having trouble getting it to fire for more than just the initial callback.

    I’d like to debug the flash as well.

    Thanks.

  4. I’d like to do the following:

    – detect if the user has 1024*768
    – if so, then set automatically zoom to 90% OR warn him to change
    his zoom manually to 90%

    Is this possible?

    — Shaman

  5. Hi Shaman,

    even this might not be the best solution, this is possible – at least the second version, where you gave the user any kind of warning to set his zoom. As far as i know there is no way to set the browsers zoom by any script.

    This will look something like this:

            <script type="text/javascript">
    			var swfZoomDetectionConfig = {
    				'onZoomChange': function(obj){
    					var xSize = document.documentElement.clientWidth;
    					var ySize = document.documentElement.clientHeight;
     
    					if( (parseInt(xSize,10)<1024 || parseInt(ySize,10)<768) && obj.scale>0.9 ){
    						alert( 'Please use your browser zoom.' );
    					}
    				},
    				'getInitIfOne': true,
    				'initCallOnly': true,
    				'frameRate': 25
    			}
    		</script>

    cheers,
    Sebastian

  6. Hi!
    After searching for a looong time, I think this might be the solution I’m seeking. However, I can’t quite figure it out.

    First of all:
    When I download your swfZoomDetection (ZIP) and test it in my browser, I get no alert window – neither initially, nor when I change the zoom level and refresh the browser window. Am I supposed to get a window like this, or have I misunderstood something? I also tried with a custom alert:

    'onZoomChange': function(obj){ alert( 'TESTING' ) },

    … but nothing happened.

    What I really want to achieve is this:
    If the window is zoomed, I want the user to be redirected to another web page. If the window is not zoomed, I want the user to be redirected to customized versions of my web page (based on screen resolution).

    To enlight you further with my case, here’s my screen resolution detection script:

    <SCRIPT language="JavaScript">
    <!--
    // small
    if ((screen.width>=1024) && (screen.width<1280))
    {
     window.location="0_framside/1_small/849x507.html";
    }
     
    // medium
    else if ((screen.width>=1280) && (screen.width<1400))
    {
     window.location="0_framside/2_medium/1105x507.html";
    }
     
    // large
    else if ((screen.width>=1400) && (screen.width<1600))
    {
     window.location="0_framside/3_large/1225x639.html";
    }
     
    // xlarge
    else if ((screen.width>=1600) && (screen.width<1920))
    {
     window.location="0_framside/4_xlarge/1425x789.html";
    }
     
    // manual
    else
    {
      window.location="resolution.html";
    }
    //-->
    </SCRIPT>

    The problem I had was this:
    In IE with a screen resolution of 1280×1024, the page 1105×507.html SHOULD be opened (the medium sized version), BUT instead the page 849×507.html gets opened (the small version).

    Why all these versions?
    The actual target pages contain a bitmap-based Flash app, which naturally is set to ’no scale‘ (since it’s bitmap). I further have a fullscreen-option button. With a total of four versions, the app looks good on screen resolution widths from 1024 to 1280 (small version), at 1280 (medium version), from 1400-1440 (large version) an from 1600-1920 (xlarge version). Within all versions there can be screen resolutions with various heigths (for example both 1280×768 and 1280×1024). Since the height also can vary so much (and some people have 4:3 while others have widescreen), I have implemented the fullscreen-option.

    Ok, this might be better explained if I show you …

    The pages are in development, but if you go here:
    http://www.kollalfa.com/temp_LesForMeg/index2.html

    … you will be redirected to the start page (after the above script has been evoked). If you click on the door to the right, you enter a ‚room‘ where the fullscreen-option resides.

    Sorry for blabbering, but I’m not quite confident with javascript (thus I use a lot of words to explain things that might not even be complex at all) …

    Superthanks in advance, if anyone can help me with this issue!

  7. Hi Håvard,

    first of all you should use the downloaded zoom detection script within an local server environment. So the script should be running in a server context ( http://localhost:1234/xzy/ ). If you directly open it from filesystem ( file://whatver/is/the/path/ ) this will not work with the security model of the flash player, which is used internally. You could test it from your website.

    The screen size detection should be correct so far. For me it’s working on FF and IE8. Maybe you have to check if its handling your screensize parameter correct. Maybe you have to wrap the screen.width within an parseInt( value ).

    if (( parseInt(screen.width,10)>=1024) && ( parseInt(screen.width,10)<1280)){

    cheers,
    Sebastian

  8. Ah, of course it would have to reside within a web server – how stupid of me …

    To my defense – I did also upload the files to a web server, but I viewed the page in Safari using the clickToFlash-plugin (http://clicktoflash.com/), and probably didn’t click on the Flash to activate it (thus, nothing happened, of course).

    Once I activated the Flash in Safari, or opened it in Firefox, or on my local web server, it worked perfectly!

    So now I can easily achieve what I intended, by replacing your initial

    function(obj){ alert(obj.scale) }

    with

    function(obj){ window.location="resolution.html" }

    So, thanks a bunch! However …

    I realize this still wouldn’t be the optimal solution. The best thing is if the user won’t have to make any manual choices at all. So I will try the parseInt-wrapping-thingy and do some testing. Hopefully you’re right (about the screen size detection script), and that my father in law’s old PC with IE was the only occasion where the screen size detection script didn’t work properly …

    Thanks again!

  9. Sorry to bother you again, but what if I want to present the result inside the body-tag (not in a pop-up), within an if else-statement? Like this:

    (if zoom level == 1)
    Your current zoom level is: 1.22. Please reset to default size by pressing Ctrl + 0 (Windows) or Command + 0 (OS X)

    (else)
    Your zoom level is OK. Please proceed.

    Thanks again!

  10. Arggh, my head is not straight today … I meant the other way around, of course:

    (if zoom level == 1)
    Your zoom level is OK. Please proceed.

    (else)
    Your current zoom level is: 1.22. Please reset to default size by pressing Ctrl + 0 (Windows) or Command + 0 (OS X)

  11. For some obscure reason the event failed to be triggered in FF3.6.3 after the initial call.

    line 95 fix

    $('#'+this._nodeId).css('position', 'absolute').css('left', (- 1 * (this._detectSWFWidth-1)) + 'px').css('bottom', (- 1 * (this._detectSWFHeight-1)) + 'px');

  12. Hi, Sebastian, thanks for your solution.
    I have a problem: in Safari 4 or FireFox 3.6 there is a feature – Zoom Text Only. If I uses this feature your solution does not works. Can you make a script for this problem?

  13. How to use this to dedect zoom levelt in silverlight application and adjust silverlight application fonts for best readability?

  14. Hi guys, sorry for late replay.

    @Konstantin: This is in deed a bit harder to detect. But i’ll try. But time is low currently :(

    @Andrus: Sorry, but i have no detailed knowlegde about silverlights capabilities. I know you can use Javascript inside. But my solution uses an instance of flash. So i dont know if i can create an flash app from within an silverlight app, to pass something back to silverlight. I don’t know how silverlight scale with the normal browser zoom.

    There is at least the possibility to pass data from JavaScript to silverlight (http://www.switchonthecode.com/tutorials/silverlight-and-javascript-interaction) just like it’s possible with flash. So you could at least detect the zoom of the complete browser ( by using my script ) and pass this to silverlight by JavaScript and adopt your font-size.

    Sorry, but i’m no silverlight expert :(

  15. Hi sebastian, i am trying to execute your script, but the Zoom change event seems to be „inactive“. I have installed your full script, no way it does not work. after investigating it seems the Flash module does not call the zoomChangeHandler. thanks for your feedback. guillaume

  16. I am working and developing under Wamp 2.0 server on windows XP SP3. So i have inserted your script inside my own Web application , all stuff seems to load properly, i have added several „alert()“ to check if the swfZoomDetection.js (init, minmax, ..) is correctly invoked, and that’s the case. But Zoom event did not seem to be triggered . any help would be welcome. thanks Guillaume

    1. hi guillaume,

      could you please try to move the javascript include under the definition of the config variable ? looks like the configuration isn’t taken. maybe the ready event isn’t handled as it should be.

      cheers,
      Sebastian

  17. As always, these hacks don’t work.

    After correcting the script paths still get ‚object does not support method‘

    You would think that you would be able to have at least a working example!!!

  18. Jimmy, did you notice this post is from December of last year and there are several comments from people remarking on how it worked for them at the time? Sometimes examples become outdated as browsers/applications update.

    I’m sure people would appreciate if you read everything before wagging your internet finger at people and come off as a jerk.

    Thanks.

    1. Hi Unabus,

      the request for the javascript file failed. Sorry i see that there is a error in the example file. In the example the javascript file is referenced by „../javascript/swfZoomDetection.js“ this is of course wrong. For the example it has to be „javascript/swfZoomDetection.js„.

      I’ll update this asap. Sorry for that.

      cheers,
      Sebastian

  19. Hi,

    I liked the solution but I have a problem here. I need to set the browser zoom level to 1 at the load of the application and need to block the zoom level if the user tries to do mousewheel scroll up or down and doing any other zoom in action.

    How can we achieve that?

    1. Hi Appy,

      sorry for the late reply. I overlooked some older comments and found them during email archiving.
      As far as i know you can’t change the zoom level of the browser. This is a users setting and can’t ( and should not be ) influenced by a script. You just can recognice this case and get the user a hint ( „… this is best shown without browser zoom“). Of course it would be better to react on this and „fix“ the problems by your app.

      cheers.
      Sebastian

  20. In chrome on windows, a few issues: (1) not getting precise zoom information (e.g. alert is telling me 50% instead of 57% as reported by the browser). More grievous is that 50% and 57% events are sometimes not fired at all. I don’t know why this is the case; your code looks complete.

  21. tip: to increase the accuracy open swfZoomDetection.js and change _detectSWFWidth and _detectSWFHeight to 100. It will give an extra decimal point when calculating the zoom.

    works like a dream in IE, chrome and firefox.

    got it to resize the flash content as the zoom levels change.

    Thanks

  22. Hi Sebastian,

    Brilliant, thank you for your hard work on this plugin. One of my questions was answered in the comments above.

    One issue I had when integrating your plugin is that you may need to add ‚var ‚ on line 59 of swfZoomDetection.js

    Other than that, spot on!

    Cheers :)

  23. I am chinese, your share helped me a lot, I just want to say Thank You now !
    In my country, QQ Space has its Zoom Detect way, but they have not share his code
    even some people declear its patent, hehehe

    Thank you !

  24. I see you don’t monetize your site,i read awesome article how to earn some additional money and increase traffic
    using one simple method, just search in google for: Twardziel advices

Schreibe einen Kommentar zu Sebastian Martens Antworten abbrechen

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert