Created
February 25, 2020 12:20
-
-
Save leMaur/ebd205dc41b4617ecc23f8a07c8ed302 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
;(function(window, document) { | |
window.toggable = function() { | |
return { | |
// Local variables | |
show: false, | |
rand: Math.random().toString(36).substr(2, 10), | |
bodyNeedsOverflowHidden: false, | |
originalOverflow: '', | |
// Get a unique id | |
id() { | |
return `toggable-${this.rand}` | |
}, | |
// Open the toggable component | |
open(bodyNeedsOverflowHidden) { | |
// change the toggable component state to open | |
this.show = true | |
// store the original body overflow value | |
this.originalOverflow = document.body.style.overflow | |
// cast variable to boolean | |
this.bodyNeedsOverflowHidden = !!bodyNeedsOverflowHidden | |
if (this.bodyNeedsOverflowHidden && this.show) { | |
// set the new body overflow value | |
document.body.style.overflow = 'hidden' | |
} | |
}, | |
// Close the toggable component | |
close() { | |
// change the toggable component state to close | |
this.show = false | |
if (this.bodyNeedsOverflowHidden) { | |
// restore the body overflow value | |
document.body.style.overflow = this.originalOverflow | |
} | |
}, | |
// Toggle the toggable component state | |
toggle(bodyNeedsOverflowHidden) { | |
// change the toggable component state | |
this.show = !this.show | |
// cast variable to boolean | |
this.bodyNeedsOverflowHidden = !!bodyNeedsOverflowHidden | |
if (this.show) { | |
// store the original body overflow value only if did not already | |
this.originalOverflow = document.body.style.overflow | |
} | |
if (this.bodyNeedsOverflowHidden) { | |
// toggle the body style value | |
if (this.bodyNeedsOverflowHidden && this.show) { | |
document.body.style.overflow = 'hidden' | |
} else { | |
document.body.style.overflow = this.originalOverflow | |
} | |
} | |
}, | |
// Check if the component is opened | |
isOpen() { | |
return this.show === true | |
}, | |
} | |
} | |
})(window, document); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment