Last active
June 28, 2017 11:22
-
-
Save ryanmaffey/5b799d19cb8abcf6a42a2fbe95024f9f to your computer and use it in GitHub Desktop.
Dispatches events on the window object whenever the screen is resized horizontally or vertically (or both).
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
/******************************************************************************* | |
* One way screen resize events. | |
* ============================= | |
* Dispatches events on the window object whenever the screen is resized | |
* horizontally or vertically (or both). | |
* | |
* Horizontal resize. | |
* ------------------ | |
* If the screen has been resized horizontally, the "horizontalResize" event is | |
* dispatched. Example usage: | |
* | |
window.addEventListener("horizontalResize", function () { | |
console.log("Horizontally resized!"); | |
}); | |
* | |
* Vertical resize. | |
* ---------------- | |
* If the screen has been resized vertically, the "verticalResize" event is | |
* dispatched. Example Usage: | |
* | |
window.addEventListener("verticalResize", function () { | |
console.log("Vertically resized!"); | |
}); | |
******************************************************************************/ | |
/** | |
* 1. Create the events. | |
* 2. Initialise the events with their name. | |
* 3. Store the window width and height. | |
* 4. On window resize, if the current window width differs from the stored | |
* window width, dispatch the "horizontalResize" event and update the stored | |
* window.width. | |
* 5. On window resize, if the current window height differs from the stored | |
* window height, dispatch the "verticalResize" event and update the stored | |
* window.height. | |
*/ | |
(function () { | |
// [1] | |
var horizontalResizeEvent = document.createEvent("Event"), | |
verticalResizeEvent = document.createEvent("Event"); | |
// [2] | |
horizontalResizeEvent.initEvent('horizontalResize', true, true); | |
verticalResizeEvent.initEvent('verticalResize', true, true); | |
// [3] | |
var windowSizes = { | |
width: window.innerWidth, | |
height: window.innerHeight | |
}; | |
window.addEventListener("resize", function () { | |
// [4] | |
if (window.innerWidth != windowSizes.width) { | |
window.dispatchEvent(horizontalResizeEvent); | |
windowSizes.width = window.innerWidth; | |
} | |
// [5] | |
if (window.innerHeight != windowSizes.height) { | |
window.dispatchEvent(verticalResizeEvent); | |
windowSizes.height = window.innerHeight; | |
} | |
}); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment