Thanks to ejohn.org for the jQuery logo.
Responsive websites involve changing states/visibility of not just html elements but jQuery functionality as well. To accomplish this, I’ve come up with some code that does the following:
- Set up a time delay that fires the window resize function only after the resize is complete
- Check the viewport size and do something if the width is less than a certain amount, usually smaller than 768px wide ipad in portrait, but not always. This usually coincides with a very specific desktop to mobile breakpoint. A good example of this is toggling a mobile menu.
- Fire a callback that does this viewport check even if the browser is refreshed
See the code below and let me know how you’d improve it! Be advised I use this code with jQuery 1.11 and haven’t tested it in jQuery v2 yet.
/*make the window resize wait till the end*/
var debouncer = function(func, timeout) {
var timeoutID, timeout = timeout || 2; // 200 original time but is jerky
return function() {
var scope = this,
args = arguments;
clearTimeout(timeoutID);
timeoutID = setTimeout(function() {
func.apply(scope, Array.prototype.slice.call(args));
}, timeout);
};
};
/* Check window width and then do something to something but wait till window is finished resizing with debouncer */
var windowWidth = $(window).width();
/*Add responsiveness in*/
var resize = function() {
debouncer(new function() {
if (($(window).width() < 768)) {
/*do something*/
} else {
/*or do something else*/
}
});
};
/* call the function to make sure it happens on page load not just page resize */
$(window).resize(function() {
resize();
});
Nice tutorials on jquery when working on responsive design. You can find more related about jquery here also
http://jqueryplugins.net/tutorials/
Sweet thanks.