jQuery function to toggle based on viewport width

2nd July 2015
All posts

jQuery logo

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:

  1. Set up a time delay that fires the window resize function only after the resize is complete
  2. 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.
  3. 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(); });

Tags:

Nathaniel Flick

I'm a Front End Web Developer passionate about usability. My primary specialties are HTML5, CSS3, SCSS, LESS, and jQuery and I am very familiar with Foundation and Bootstrap frameworks. I've worked on top of and with Rails, Python, and ASP.net/Umbraco back end frameworks.