Skip to content

Instantly share code, notes, and snippets.

@ryanmaffey
Last active June 28, 2017 11:22
Show Gist options
  • Save ryanmaffey/5b799d19cb8abcf6a42a2fbe95024f9f to your computer and use it in GitHub Desktop.
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).
/*******************************************************************************
* 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