Safran Ali
Safran Ali

Reputation: 4497

How to detect in jquery if screen resolution changes?

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?

Upvotes: 35

Views: 81388

Answers (6)

Arnaud Méhat
Arnaud Méhat

Reputation: 21

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>

Upvotes: 2

Pierre
Pierre

Reputation: 19071

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!');
});

Upvotes: 9

Willem Mulder
Willem Mulder

Reputation: 13994

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!

Upvotes: 3

Nathan
Nathan

Reputation: 11149

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.

Upvotes: 40

talha2k
talha2k

Reputation: 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.

Upvotes: 1

Benno
Benno

Reputation: 3008

$(window).resize()

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

$(window).resize(function() {

alert('window was resized!');

});

Upvotes: 24

Related Questions