D
D
dm2015-09-05 20:06:17
css
dm, 2015-09-05 20:06:17

Menu-accordion. How to collapse inactive items?

How is the folding of inactive menu items done in the accordion menu? So that you open one, and the previously open one closes.
HTML

<ul class="accordeon">

  <li><a class="btn-menu" href="#">Верхний пункт</a>
    <ul class="sub-menu">
      <li><a class="sub-menu__item" href="#">Первое меню 1</a></li>
      <li><a class="sub-menu__item" href="#">Первое меню 2</a></li>
      <li><a class="sub-menu__item" href="#">Первое меню 3</a></li>
      <li><a class="sub-menu__item" href="#">Первое меню 4</a></li>
    </ul>
  </li>

  <li><a class="btn-menu" href="#">Средний пункт</a>
    <ul class="sub-menu">
      <li><a class="sub-menu__item" href="#">Второе меню 1</a></li>
      <li><a class="sub-menu__item" href="#">Второе меню 2</a></li>
      <li><a class="sub-menu__item" href="#">Второе меню 3</a></li>
      <li><a class="sub-menu__item" href="#">Второе меню 4</a></li>
    </ul>
  </li>

  <li><a class="btn-menu" href="#">Нижний пункт</a>
    <ul class="sub-menu">
      <li><a class="sub-menu__item" href="#">Третье меню 1</a></li>
      <li><a class="sub-menu__item" href="#">Третье меню 2</a></li>
      <li><a class="sub-menu__item" href="#">Третье меню 3</a></li>
      <li><a class="sub-menu__item" href="#">Третье меню 4</a></li>
    </ul>
  </li>

</ul>

JS
var btnMenu = document.querySelectorAll('.btn-menu'),
    subMenu = document.querySelectorAll('.sub-menu'),
    i, btn, sub;

for (i = 0; i < btnMenu.length; i++) {
    btn = btnMenu[i];
    sub = subMenu[i];

    btn.addEventListener('click', menuOpen(btn, sub));
};

function menuOpen(btn, sub) {
    return function (event) {
        event.preventDefault();
        btn.classList.toggle('btn-menu--active');
        sub.classList.toggle('sub-menu--show');
    };
};

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
Pashenka, 2015-09-05
@Chekhoved

Hide everything and open the current one

.sub-menu {
  display: none;
}

jQuery
$('.btn-menu').on('click', function() {
    $('.sub-menu').hide();
    $(this).siblings('.sub-menu').show();
});

A
Artem Yakushev, 2015-12-03
@levwvel

Dreamweaver CC Insert-jQuery UI-Accordion All that's
left is to color it

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question