2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【JavaScript】Pure JSだけでハンバーガーメニュー

Posted at

jQueryを使わずにclassの付け替えで制御する

クリックしたら「isActive」クラスをハンバーガーアイコンに追加する。

index.html
<header class="header">
    <div class="inner">
      <div class="btn js-menuIcon">
        <span></span>
        <span></span>
        <span></span>
      </div>
      <nav class="nav__drawer">
        <ul class="nav__lists">
          <li class="nav__list">
            <a href="/">Top</a>
          </li>
        </ul>
      </nav>
      <div class="js-navBg"></div>
    </div>
  </header>
main.js
// ハンバーガーメニュー
const menuIcon = document.querySelector('.js-menuIcon');
const navBg = document.querySelector('.js-navBg');

// ハンバーガーアイコンを押したら「is-active」クラスを付与してドロワーメニューが開く
menuIcon.addEventListener('click', () => {
  menuIcon.classList.toggle('isActive');
})

// 背景を押したら「is-active」クラスを取り除いてドロワーメニューを閉じる
navBg.addEventListener('click', () => {
  menuIcon.classList.remove('isActive');
})
style.css
/* sp navigation */
.js-menuIcon {
  display: block;
  cursor: pointer;
  width: 40px;
  height: 40px;
  z-index: 10;
  position: absolute;
  /* background-color: blue; */
}

.js-menuIcon span {
  width: 30px;
  height: 4px;
  background-color: #fff;
  display: block;
  transition: all 0.2s;
  position: absolute;
  left: 10px;
  z-index: 4;
  cursor: pointer;
}
.js-menuIcon span:first-child {
  margin-top: 0;
  top: 10px;
}
.js-menuIcon span:nth-child(2) {
  top: 20px;
}
.js-menuIcon span:nth-child(3) {
  top: 30px;
}

.js-menuIcon.isActive span:first-child {
  transform: rotate(45deg);
  top: 20px;
}

.js-menuIcon.isActive span:nth-child(2) {
  transform: rotate(-45deg);
  top: 20px;
}

.js-menuIcon.isActive span:nth-child(3) {
  transform: rotate(-45deg);
  top: 20px;
}

.nav__drawer {
  background-color: pink;
  width: 50%;
  height: 100vh;
  z-index: 2;
  transform: translateX(-100%);
  transition: all 0.3s;
  position: absolute;
  top: 0;
  left: -50%;
}

.isActive ~ .nav__drawer {
  transform: translateX(0);
  left: 0;
}

.header .inner {
  position: relative;
}

.isActive ~ .js-navBg {
  background: rgba(0, 0, 0, 0.5);
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1;

  cursor: pointer;
}

.nav__list a {
  display: block;
  padding: 1rem 0;
}

.nav__list a:hover {
  background-color: orange;
}
2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?