본문 바로가기
Js

toggle menu, 햄버거 토글

by 영감은어디에 2024. 6. 28.
document.body.classList.add('js');
var toggle    = document.querySelector('#toggle-navigation');
var menu      = document.querySelector('#menu');
var menuItems = document.querySelectorAll('#menu li a');

toggle.addEventListener('click', function(){
  if (menu.classList.contains('is-active')) {
    this.setAttribute('aria-expanded', 'false');
    menu.classList.remove('is-active');
  } else {
    menu.classList.add('is-active'); 
    this.setAttribute('aria-expanded', 'true');
  }
});

 

<nav>
  <button id="toggle-navigation" aria-expanded="false">
    <span class="icon-menu"></span><span class="hidden">Menu</span>
  </button>
  <ul id="menu">
    <?php foreach ($navigation as $link) { ?>
    <li>
        <a href="category.php?id=<?= $link['id'] ?>" 
        <?= ($section == $link['id'] ) ? 'class="on" aria-current="page"' : '' ?>>
        <?= html_escape($link['name']) ?>
        </a>
    </li>
    <?php } ?>
  </ul>
</nav>

토글햄버거메뉴 

<a href="#" class="menu">
    <span></span>
    <span></span>
    <span></span>
    <span></span>
</a>
$('.menu').click(function(e){
    e.preventDefault();
    $(this).toggleClass('active');
})
.menu{display: block;position: relative; transition: 0.3s ease-in-out;width: 45px; height: 34px;}
.menu span{position: absolute; height: 8px; border-radius: 4px; width: 100%; background-color: #000; transition: all 0.2s; top: 0;}
.menu span:nth-child(1){top: 0;}
.menu span:nth-child(2), .menu span:nth-child(3){top:13px;}
.menu span:nth-child(4){top: 26px;}
.menu.active span{opacity: 0;}
.menu.active span:nth-child(2){opacity: 1; transform: rotate(45deg);}
.menu.active span:nth-child(3){opacity: 1; transform: rotate(-45deg);}