Last active
June 6, 2017 17:53
-
-
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
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
/** | |
* 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