35

How can I make it so that each time when user changes the screen resolution size [not the browser window], the page perform a function?

Safran Ali
  • 4,477
  • 9
  • 40
  • 57
  • 1
    You *might* be able to poll `screen.width` and/or `screen.height`. Though it could also be that in that case a `resize` event is triggered on the window. Then you don't have to poll, but just attach a `resize` event handler and check whether the `screen.X` values changed. – Felix Kling Dec 20 '11 at 12:57

6 Answers6

39

Ok, so you're using jQuery. So let's make a custom event for it.

(function () {
    var width = screen.width,
        height = screen.height;
    setInterval(function () {
        if (screen.width !== width || screen.height !== height) {
            width = screen.width;
            height = screen.height;
            $(window).trigger('resolutionchange');
        }
    }, 50);
}());

Now $(window).bind('resolutionchange', fn) should do what you want.

Nathan MacInnes
  • 11,033
  • 4
  • 35
  • 50
  • Nice, didn't know that we had access to 'screen', although it makes sense if I think about those browser statistics that include a screen resolution :) – Willem Mulder Dec 20 '11 at 15:31
  • 1
    This is much simpler http://stackoverflow.com/a/11464779/579854 I do not know, may be there are some hidden limitations in this solution (may be too slow) comparing to top answers in this question? – Vasiliy Toporov Feb 07 '14 at 14:40
  • 1
    @VasiliyToporov, the OP specifically said not the window size. – Nathan MacInnes Feb 08 '14 at 17:20
24

$(window).resize()

http://api.jquery.com/resize/

$(window).resize(function() {

alert('window was resized!');

});
Benno
  • 3,008
  • 3
  • 26
  • 41
  • 4
    Please read the question again. This is not what was asked for. – Felix Kling Dec 20 '11 at 12:58
  • Just noticed :p In that case, I believe you may have to go with what even Facebook does? Use cookies or localStorage based on screen width/height? Use a setInterval with that and if its different, do something. As far as I was aware though, 'resize' is triggered when screen resolution is changed, because it would change the viewport dimensions? I guess thats only if the windows maximised though :\ – Benno Dec 20 '11 at 13:00
  • 4
    jQuery + jQuery Mobile use: $(window).on("resize, orientationchange"), function(){ alert('window was resized!'); }); – Jose Nobile Aug 05 '13 at 06:39
9

Try tracking screen.width and screen.height. They will return different values when changing the screen resolution. More info here.

function doSomething(){
    if ( screen.width < 1280 ){
        console.log('Too small')
    }else{
        console.log('Nice!')
    }
}

However, as far as i know there are no events triggered when changing the screen resolution; Which means you cannot do this $(screen).resize(function(){/*code here*/});

So another way to do it will be using a setTimeout() such as: [not recommended]

var timer,
    checkScreenSize = function(){
        if ( screen.width < 1280 ){
            console.log('Too small')
        }else{
            console.log('Nice!')
        }
        timer = setTimeout(function(){ checkScreenSize(); }, 50);
    };

checkScreenSize();

The recommended version will be using the requestAnimationFrame. As described here by Paul Irish. Because if you're running the loop in a tab that's not visible, the browser won't keep it running. For better overall performance.

// shim layer with setTimeout fallback
window.requestAnimFrame = (function(){
  return  window.requestAnimationFrame       || 
          window.webkitRequestAnimationFrame || 
          window.mozRequestAnimationFrame    || 
          window.oRequestAnimationFrame      || 
          window.msRequestAnimationFrame     || 
          function( callback ){
            window.setTimeout(callback, 1000 / 60);
          };
})();


// usage: 
// instead of setInterval(checkScreenSize, 50) ....

(function loop(){
  requestAnimFrame(loop);
  checkScreenSize();
})();

[update]

For those who want to implement requestAnimationFrame in Nathan's answer, there you go; A custom jQuery event that is triggered on resolution change, uses requestAnimationFrame when available for less memory usage:

window.requestAnimFrame = (function(){
    return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function( callback ){ window.setTimeout(callback, 1000 / 60); };
})();

var width = screen.width,
    height = screen.height,
    checkScreenSize = function () {
        if (screen.width !== width || screen.height !== height) {
            width = screen.width;
            height = screen.height;
            $(window).trigger('resolutionchange');
        }
    };

(function loop(){
  requestAnimFrame(loop);
  checkScreenSize();
})();

Usage:

$(window).bind('resolutionchange', function(){
    console.log('You have just changed your resolution!');
});
Community
  • 1
  • 1
Pierre
  • 18,643
  • 4
  • 41
  • 62
  • Nice. +1, although I still prefer my answer for simplicity! ;) – Nathan MacInnes Jan 10 '12 at 15:57
  • Haha, i also preferred your answer on mine! You got great prototyping skills! Therefore i based my answer on yours :). [Yes, i insist on using the ReqAnimFrm when available :D] – Pierre Jan 10 '12 at 16:12
3

Because you can only from within a specific browser-window check for changes within that same browser-window, it is not possible to know about resolution-changes of the display.

However, if the browser window also changes when the display resolution changes, you can catch this with a listener on the window.width and window.height.

edit: It seems we can obtain the information you want from the global 'window.screen' object. See https://developer.mozilla.org/en/DOM/window.screen.height and https://developer.mozilla.org/en/DOM/window.screen.width for more information!

Willem Mulder
  • 12,974
  • 3
  • 37
  • 62
  • I'm not aware of an event that tells you when the resolution changes, but you can use `setInterval()` to check `screen.width` and `screen.height` every x milliseconds and take some action if they change... – nnnnnn Dec 20 '11 at 13:05
  • Not true. As most of the other answers say `screen.width` and `screen.height` (slightly different accessor for IE) return the screen resolution. And if you are listening for `window.width` and `window.height`, why not just use `window.onresize`. – Nathan MacInnes Dec 20 '11 at 14:17
2

Try this js :

var width = $(window).width();
var height = $(window).height(); 
var screenTimer = null;

function detectScreen (){
    $(window).resize(function() {
      height = $(window).height(); 
      width = $(window).width(); 
        getScreen ();
    });

    function getScreen (){
        return { 'height' : getHeight (), 'width': getWidth () };
    }
    screenTimer = setInterval ( getScreen (), 50 );
}
function getHeight (){
    console.log ( 'height: ' + height);
    $('#height').text(height);
    return height;
}
function getWidth (){
    console.log ( 'width: ' + width);
    $('#width').text(width);
     return width;   
}
detectScreen ();

$('#go').click (function (){
    detectScreen ();
});

$('#stop').click (function (){
    clearInterval(screenTimer);
});

And for html :

<span id="stop">Stop</span> | <span id="go">Go</span>
<br>
<div>height: <span id="height"></span> px</div>
<div>width: <span id="width"></span>px </div>
1

The following function fires on window re-sizing as well as resolution change and also has a delay to avoid multiple calls while the user is re-sizing the window.

I've set up a fiddle for you here:

http://jsfiddle.net/EJK5L/

Change your resolution and function alerts you. you can perform any function, what you want.

Hope this helps.

talha2k
  • 24,937
  • 4
  • 62
  • 81