Skip to content

Instantly share code, notes, and snippets.

@sniffdk
Created August 12, 2014 23:36
Show Gist options
  • Save sniffdk/fcb91b77e8db15e0b0c3 to your computer and use it in GitHub Desktop.
Save sniffdk/fcb91b77e8db15e0b0c3 to your computer and use it in GitHub Desktop.
Small utility functions for handling responsive changes to javascript stuff.
var breakpoints = {
xs: 480,
sm: 768,
md: 992,
lg: 1200
},
currentWidth = 0,
currentBreakpoint = "",
breakpointMethods = []; // array of methods to be run whenever a breakpoint change is registered
/*
Taken from Stack Overflow, most precise method I've found yet
http://stackoverflow.com/q/1766861
*/
function getViewport() {
var e = window, a = "inner";
if (!("innerWidth" in window)) {
a = "client";
e = document.documentElement || document.body;
}
return { width: e[a + "Width"], height: e[a + "Height"] };
};
function responsive() {
var oldBreakpoint = currentBreakpoint,
newBreakpoint,
width = currentWidth = getViewport().width;
if (width < breakpoints.xs) { newBreakpoint = "xxs"; }
else if (width < breakpoints.sm) { newBreakpoint = "xs"; }
else if (width < breakpoints.md) { newBreakpoint = "sm"; }
else if (width < breakpoints.lg) { newBreakpoint = "md"; }
else { newBreakpoint = "lg"; }
currentBreakpoint = newBreakpoint;
// Only run the breakpoint methods if the breakpoint actually changed
if (oldBreakpoint === newBreakpoint) {
return;
}
for (var i = 0; i < breakpointMethods.length; i++) {
breakpointMethods[i](); // add relevant parameters if needed
}
}
(function ($) {
var w = $(window);
/*
easy way of throttling calls to the resize event
listen to the resize event once, run the all the responsive methods, wait, repeat
*/
var responsiveListener = function () {
w.one("resize", function () {
responsive();
setTimeout(responsiveListener, 200);
});
};
// kick of the listener and run all the methods once immediately
responsiveListener();
responsive();
// Run again when everything, including images, is loaded
w.load(function () {
responsive();
});
})(jQuery);
function DoResponsiveWork() {
// use this approach to target more breakpoints at the same time
if (currentWidth < breakpoints.sm) {
// disable slider or something
}
else {
// enable it again or something
}
}
function DoResponsiveWork2() {
// use this approach to target one specific breakpoint
if (currentBreakpoint == "xxs") {
// Change slider layout or something
}
else {
// Change it back again
}
}
// Add methods to the array so that they will be run every time we change breakpoint
breakpointMethods.push(DoResponsiveWork);
breakpointMethods.push(DoResponsiveWork2);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment