How to open Bootstrap dropdown programmatically

后端 未结 16 1922
轮回少年
轮回少年 2020-12-01 13:56

I\'m trying to open a Bootstrap dropdown when I click a item of another dropdown.

The idea is to select a city from the first drop down - then the script will auto o

16条回答
  •  难免孤独
    2020-12-01 14:12

    in Bootstrap 4.x, following components need to be effected:

    • li > .nav-item .dropdown
      • a > .nav-link > aria-expanded
    • div > .dropdown-menu

    Adding a click event listener, which triggers toggling a class and a bool value, for those classes make dropdown work with pure javascript as follows:

    let status = false
    const nav = document.getElementsByClassName('nav-item dropdown')[0]
    nav.addEventListener('click', toggleDropdown)
    function toggleDropdown () {
       if (status) {
          nav.classList.add('show')
          document.getElementsByClassName('nav-link dropdown-toggle')[0].setAttribute('aria-expanded', ' + status + ')
          document.getElementsByClassName('dropdown-menu').classList.add('show')
       } else {
          nav.classList.remove('show')
          document.getElementsByClassName('nav-link dropdown-toggle')[0].setAttribute('aria-expanded', ' + status + ')
          document.getElementsByClassName('dropdown-menu').classList.remove('show')
       }
       return status = !status
    }
    

提交回复
热议问题