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?

1
  • 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. Dec 20, 2011 at 12:57

6 Answers 6

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.

3
  • 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 :) Dec 20, 2011 at 15:31
  • 1
    This is much simpler 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? Feb 7, 2014 at 14:40
  • 1
    @VasiliyToporov, the OP specifically said not the window size. Feb 8, 2014 at 17:20
24

$(window).resize()

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

$(window).resize(function() {

alert('window was resized!');

});
3
  • 4
    Please read the question again. This is not what was asked for. Dec 20, 2011 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, 2011 at 13:00
  • 4
    jQuery + jQuery Mobile use: $(window).on("resize, orientationchange"), function(){ alert('window was resized!'); }); Aug 5, 2013 at 6: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!');
});
2
  • Nice. +1, although I still prefer my answer for simplicity! ;) Jan 10, 2012 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, 2012 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!

2
  • 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, 2011 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. Dec 20, 2011 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.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.