Skip to content

Instantly share code, notes, and snippets.

@ten1seven
Created February 2, 2017 16:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ten1seven/8e98f0ee26089a041264ae47e707e1d9 to your computer and use it in GitHub Desktop.
Save ten1seven/8e98f0ee26089a041264ae47e707e1d9 to your computer and use it in GitHub Desktop.
export default class MobileMenu {
constructor(el) {
this.el = el
this.setVariables()
this.setUpListeners()
}
setVariables() {
this.toggle = this.el.querySelector('[data-mobile-menu="toggle"]')
this.overlay = this.el.querySelector('[data-mobile-menu="overlay"]')
this.toggled = false
// named event handler for adding/removing
this.onMenuDismiss = this.menuDismiss.bind(this)
}
setUpListeners() {
this.toggle.addEventListener('click', this.toggleMenu.bind(this))
}
menuDismiss(e) {
if (this.toggled === true && !this.overlay.contains(e.target)) {
this.closeMenu()
}
}
toggleMenu() {
this[(this.toggled === true) ? 'closeMenu' : 'openMenu']()
}
openMenu() {
this.overlay.setAttribute('aria-expanded', 'true')
this.toggle.classList.add('-active')
this.overlay.classList.add('-active')
this.toggled = true
// 5ms delay before binding prevents event bubbling from triggering close immediately after opening
window.setTimeout(function() {
document.body.addEventListener('click', this.onMenuDismiss)
}.bind(this), 5)
}
closeMenu() {
this.overlay.setAttribute('aria-expanded', 'false')
this.toggle.classList.remove('-active')
this.overlay.classList.remove('-active')
this.toggled = false
document.body.removeEventListener('click', this.onMenuDismiss)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment