본문 바로가기
Javascript

토글 버튼 구현하기 (+ 'X'자 버튼 만들기)

 

1. 토글의 유래

먼저 토글의 뜻을 알아보자. 단어의 시작은 의류에 용어였다.

토글은 더블 코트의 달린 길다란 단추를 의미하는 단어였다.

 

출처 : https://zigzag.kr/catalog/products/118990107
출처 : https://www.11st.co.kr/products/2817237814

 

흔히 떡볶이 코트라고 불리는 외투의 단추를 자세히 보며 알 수 있다.

이와 비슷하게 생긴 on/off스위치를 토글 스위치라 불렀으며

현재는 두가지 상태를 하나의 버튼으로 제어할 수 있을 때 '토글'이라 불린다.

 

 

 

2. 토글 버튼 구현

이제는 토글 버튼을 가장 많이 사용하는 메뉴버튼을 만들어보자.

 

제작할 버튼은 아래와 같다.

햄버거 버튼을 클릭할 경우, 하단으로 메뉴가 내려온다.

다시 한번 클릭할 경우 하단 메뉴이 올라가면서 숨겨진다.

 

html

<body>
  <div class="wrap">
    <nav class="navi-wrapper">
      <div class="top-wrap">
       <h1>LOGO</h1>
        <button class="btn-menu">
          <span class="bar"></span>
        </button>
      </div>
      <ul class="navi-wrap">
        <li class="navi">
          <a href="#">menu1</a>
        </li>
        <li class="navi">
          <a href="#">menu2</a>
        </li>
        <li class="navi">
          <a href="#">menu3</a>
        </li>
      </ul>
    </nav>
  </div>
</body>

 

CSS

body {font-size: 10px; background-color: #eef5fa;}
.wrap {max-width:calc(600px - 1rem); margin: 0 auto;}
.navi-wrapper {background-color: #fff; box-sizing: border-box;}
.top-wrap {box-shadow: 0px 3px 10px 0px #00000020; display: flex; align-items: center; justify-content: space-between;}
.top-wrap h1 {font-weight: 700; font-size: 1.8rem; padding: .5rem 0 .5rem 1rem;}
.btn-menu {position: relative; width: 45.8px; height: 45.8px; background-color: #fff; cursor: pointer;}
.btn-menu:hover {background-color: #eee;}
.btn-menu .bar {width: 1.5rem; height: 2px; background-color: #000; display: block; margin: 0 auto;}
.btn-menu .bar::before,
.btn-menu .bar::after {transform: translate(-50%, -50%); content: ''; position: absolute; width: 1.5rem; height: 2px; background-color: #000; top: 30%; left: 50%;}
.btn-menu .bar::after {top: 70%;}
.navi-wrap {display: none; transition: 1s;}
.navi-wrap.active {display: block;}
.navi-wrap.active .navi {padding: 1rem; font-size: 1rem; border-bottom: 1px solid #eee; cursor: pointer;}
.navi-wrap.active .navi:hover {background-color: #eee;}

 

 

적용된 모습은 아래 사진과 같다

기본 세팅으로 navi-wrapdisplay: none;을 주어 하단 메뉴를 감춘다.

js는 아래 포스팅과 구조가 매우 유사하지만 대신 .classList.toggle()사용한다.

특히 큰장점은 classList.add() .classList.remove를 따로 작성하지않는 것이다.

▼참고 포스팅

 

모달 팝업 만들기 (240105 주의 사항 추가)

📒 모달과 팝업, 모달팝업? 퍼블리싱을 하다보면 모달과 팝업을 구현해야 할 경우가 많다. 현재는 모달과 팝업창을 특별히 구분하지않으며 함께 사용하여 모달팝업이라 부르기도 한다. 구분 시

yurim99.tistory.com

 

js

const btnMenu = document.querySelector('.btn-menu');
const naviWrap = document.querySelector('.navi-wrap')
btnMenu.addEventListener('click', () => {
	naviWrap.classList.toggle('active')
});

 

 

 

3. 햄버거 버튼에서 X자 버튼으로

여기서 좀 더 인터렉티브한 애니메이션을 추가해보자.

 

가장 자주 사용하는 애니메이션 효과 중 하나로,

햄버거 버튼이 X자 버튼으로 바뀌고 다시 클릭하면 원상태로 변경하게 만들자.

 

간단하게 transform 속성의 rotate을 사용하면 된다.

가운데 bar는 보이지 않고 나머지 가장 끝에 있는 2개의 일직선 교차로 회전 시킨다.

이를 코드로 표현하면 아래와 같다.

/* 추가 */
.btn-menu.active > .bar {background-color: #fff;}
.btn-menu.active:hover > .bar {background-color: #eee;}
.btn-menu.active > .bar::before {transform: rotate(45deg) translate(0); top: 50%; left: 25%;}
.btn-menu.active > .bar::after  {transform: rotate(-45deg) translate(0); top: 50%; left: 25%;}
const btnMenu = document.querySelector('.btn-menu');
const naviWrap = document.querySelector('.navi-wrap')
btnMenu.addEventListener('click', () => {
	naviWrap.classList.toggle('active')
    btnMenu.classList.toggle('active') //추가
});

 

 

최종

See the Pen Untitled by yurim99 (@yurim99) on CodePen.