How to detect in jquery if screen resolution changes?
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.
$(window).resize()
$(window).resize(function() {alert('window was resized!');});
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 fallbackwindow.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!');});