Skip to content

Instantly share code, notes, and snippets.

@MuhammadKhizar7
Created August 29, 2020 18:54
Show Gist options
  • Save MuhammadKhizar7/1ac85315c7d0d4094a55e757a9f31706 to your computer and use it in GitHub Desktop.
Save MuhammadKhizar7/1ac85315c7d0d4094a55e757a9f31706 to your computer and use it in GitHub Desktop.
This for bootstrap Menu and dropdown menu without jquery
var MenuUI = {
el: {
toggle: document.getElementsByClassName('navbar-toggler')[0],
collapse: document.getElementsByClassName('navbar-collapse')[0],
dropdowns: document.getElementsByClassName('dropdown'),
},
init: function () {
let toggle = MenuUI.el.toggle
// dropdown open
MenuUI.openDropdown()
// Event listeners
window.addEventListener('resize', MenuUI.closeMenusOnResize, false)
toggle.addEventListener('click', MenuUI.toggleMenu, false)
},
openDropdown: function () {
// Add click handling to dropdowns
dropdowns = MenuUI.el.dropdowns
for (var i = 0; i < dropdowns.length; i++) {
dropdowns[i].addEventListener('click', function () {
var open = this.classList.contains('show')
MenuUI.closeMenus()
if (!open) {
this.getElementsByClassName('dropdown-toggle')[0].setAttribute(
'aria-expanded',
true
)
this.getElementsByClassName('dropdown-menu')[0].classList.toggle(
'show'
)
this.classList.toggle('show')
}
})
}
},
closeMenus: function () {
let dropdowns = MenuUI.el.dropdowns
for (var j = 0; j < dropdowns.length; j++) {
dropdowns[j]
.getElementsByClassName('dropdown-toggle')[0]
.setAttribute('aria-expanded', false)
dropdowns[j]
.getElementsByClassName('dropdown-menu')[0]
.classList.remove('show')
dropdowns[j].classList.remove('show')
}
},
toggleMenu: function () {
let collapse = MenuUI.el.collapse,
toggle = MenuUI.el.toggle
MenuUI.closeMenus()
collapse.classList.toggle('show')
toggle.classList.toggle('collapsed')
var x = toggle.getAttribute('aria-expanded')
if (x == 'true') {
x = 'false'
} else {
x = 'true'
}
toggle.setAttribute('aria-expanded', x)
},
closeMenusOnResize: function () {
let toggle = MenuUI.el.toggle,
collapse = MenuUI.el.collapse
MenuUI.closeMenus()
toggle.classList.add('collapsed')
collapse.classList.remove('show')
toggle.setAttribute('aria-expanded', false)
},
}
MenuUI.init()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment