-
-
Save kelsS/3a5d09e1f1fb4c9107a469b9e6e49598 to your computer and use it in GitHub Desktop.
Track browser size in real time, do stuff at certain breakpoints. A JavaScript media query, essentially. Borrowed from @aarongustafson.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// watch browser width on resize | |
var browser_width = 0; | |
window.watchResize(function(){ | |
browser_width = window.innerWidth || document.body.offsetWidth; | |
}); | |
// do stuff after breakpoint | |
window.watchResize(function(){ | |
var threshold = 400; | |
if ( browser_width >= threshold ) { | |
// do stuff when window is ≥ 400px wide | |
} | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function( window ) { | |
window.watchResize = function( callback ) { | |
var resizing; | |
callback.size = 0; | |
function done() { | |
var curr_size = window.innerWidth; | |
clearTimeout( resizing ); | |
resizing = null; | |
// only run on a true resize | |
if ( callback.size != curr_size ) { | |
callback(); | |
callback.size = curr_size; | |
} | |
} | |
window.addEventListener( 'resize', function() { | |
if ( resizing ) { | |
clearTimeout( resizing ); | |
resizing = null; | |
} | |
resizing = setTimeout( done, 50 ); | |
}); | |
// init | |
callback(); | |
}; | |
}(window)); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function(a){a.watchResize=function(d){var c;d.size=0;function b(){var e=a.innerWidth;clearTimeout(c);c=null;if(d.size!=e){d();d.size=e}}a.addEventListener("resize",function(){if(c){clearTimeout(c);c=null}c=setTimeout(b,50)});d()}}(window)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment