Skip to content

Instantly share code, notes, and snippets.

@graciano
Last active June 6, 2017 17:53
Show Gist options
  • Save graciano/583467fa443896e9560304422c79d703 to your computer and use it in GitHub Desktop.
Save graciano/583467fa443896e9560304422c79d703 to your computer and use it in GitHub Desktop.
addResizeEventBreakpoint.js Add given screen specific callbacks to run when resize changes from 768px breakpoint. Ensures that one of the callbacks run right after calling it
/**
* Add given screen specific callbacks to run when resize changes from 768px breakpoint
* Ensures that one of the callbacks run at the end of this function
*/
let addResizeEventBreakpoint = function(mobileCallback, desktopCallback) {
// force handleResize to run some callback at first
var mobileState = window.matchMedia("(min-width: 768px)").matches;
function handleResize() {
//run mobileCallback if resized to mobile and last function that ran was desktopCallback
if (window.matchMedia("(max-width: 768px)").matches && !mobileState) {
mobileState = true;
mobileCallback();
}
//run desktopCallback if resized to mobile and last function that ran was mobileCallback
else if (window.matchMedia("(min-width: 768px)").matches && mobileState) {
mobileState = false;
desktopCallback();
}
}
window.addEventListener('resize', handleResize);
// run for the first time
handleResize();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment