dropdown.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. (function() {
  2. document.addEventListener('DOMContentLoaded', function(event) {
  3. document
  4. .querySelectorAll('[data-toggle="dropdown"]')
  5. .forEach(function(elem) {
  6. elem.addEventListener('click', toggleDropdown)
  7. })
  8. document
  9. .querySelectorAll('.dropdown-menu')
  10. .forEach(function(elem) {
  11. elem.addEventListener('click', function(event) { event.stopPropagation() })
  12. })
  13. })
  14. function toggleDropdown(event){
  15. event.stopPropagation()
  16. event.preventDefault()
  17. var elem = event.target.closest('div').querySelector('.dropdown-menu')
  18. var open = elem.classList.toggle('is-open')
  19. if(elem.setAttribute) // not supported by IE11
  20. elem.setAttribute('aria-expanded', open ? 'true' : 'false')
  21. if(open) {
  22. window.addEventListener('click', globalCloseDropdown)
  23. } else {
  24. window.removeEventListener('click', globalCloseDropdown)
  25. }
  26. }
  27. function globalCloseDropdown(event){
  28. event.stopPropagation()
  29. event.preventDefault()
  30. event
  31. .target
  32. .querySelectorAll('.dropdown-menu.is-open')
  33. .forEach(function(elem) {
  34. elem.classList.remove('is-open')
  35. elem.setAttribute('aria-expanded', 'false')
  36. })
  37. window.removeEventListener('click', globalCloseDropdown)
  38. }
  39. }())