Skip to content

Instantly share code, notes, and snippets.

@leMaur
Created February 25, 2020 12:20
Show Gist options
  • Save leMaur/ebd205dc41b4617ecc23f8a07c8ed302 to your computer and use it in GitHub Desktop.
Save leMaur/ebd205dc41b4617ecc23f8a07c8ed302 to your computer and use it in GitHub Desktop.
;(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