無제

Vanilla Javascript_사이드바 토글 메뉴 본문

<script>

Vanilla Javascript_사이드바 토글 메뉴

yo-u-loo 2026. 6. 12. 18:41

 

Vanilla-JS-​nav-left

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=3.0">
    <title>사이드바 토글 메뉴 예제-https://youtu.be/hW67URqvWP4?list=PLpK-F7ihqVc39kaC4-77snhSpxa5umFRg</title>
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.1.0/css/all.css">
    <link rel="stylesheet" href="js5.css">
    <script src="script.js"></script>
</head>

<body>

    <main>

        <nav id="sidebar">
            <div class="toggle-btn" onclick="show()">
                <span></span>
                <span></span>
                <span></span>
            </div>

            <ul>
                <li><a href="#">January</a></li>
                <li><a href="#">February</a></li>
                <li><a href="#">March</a></li>
                <li><a href="#">April</a></li>
            </ul>
        </nav>

        <script>
            function show() {
                document.getElementById('sidebar').classList.toggle('act');
            }
        </script>

        <section>
            <header>
                <h1>Contrary to popular belief</h1>
            </header>

            <p><br></p>
            <p><br>There are many variations of passages of Lorem Ipsum available, but the majority have suffered
                alteration
                in some form, by injected humour, or randomised words which don't look even slightly believable. If you
                are
                going to use a
                passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of
                text.
                All
                the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary.</p>
            <p><br></p>
            <p><br></p>
            <p><br></p>

            <footer>
                <small>There is no one who loves pain itself, who seeks after it and wants to have it, simply because it
                    is
                    pain...</small>
            </footer>
        </section>

    </main>

</body>

</html>

 

@import url('https://fonts.googleapis.com/css?family=Quicksand&display=swap');

* {
    border: 0px solid slategray;
    margin: 0;
    padding: 0;
}

body {
    font-family: 'Quicksand', sans-serif;
    color: white;
    font-size: 1rem;
    line-height: 2rem;
}

body {
    background: url('https://images.unsplash.com/photo-1480511361210-b1b966c8d614?ixlib=rb-1.2.1&auto=format&fit=crop&w=1863&q=80') no-repeat;
    background-size: cover;
    background-position: middle center;
}

h1 {
    font-size: 2.4rem;
}

main {
    width: 100%;
    height: 100vh;
    background: rgba(0, 0, 0, 0.2);
}

#sidebar {
    position: absolute;
    width: 300px;
    height: 100vh;
    background: #000;
    left: -300px;
    transition: .4s;
    z-index: 99;
}

/* Don't make blank with id and class */
#sidebar.act {
    left: 0;
}

#sidebar ul li a {
    list-style: none;
    display: flex;
    color: #fff;
    font-size: 1rem;
    padding: 20px 24px;
    background: #000;
    cursor: pointer;
    text-decoration: none;
}

#sidebar ul li a:hover {
    background: steelblue;
}

.toggle-btn {
    position: absolute;
    top: 30px;
    left: 330px;
    cursor: pointer;
}

.toggle-btn span {
    width: 40px;
    height: 3px;
    background: #000;
    display: block;
    margin-top: 4px;
}

section {
    padding: 10%;
}

 

이번 코드는 전 세계 대부분의 반응형 웹사이트나 대시보드 관리자 페이지에서 필수적으로 사용되는 ‘사이드바 슬라이딩 메뉴(Sliding Sidebar Menu)’ 기능입니다.

버튼을 클릭하면 화면 한쪽에 숨겨져 있던 메뉴바가 부드럽게 밀려 나오고, 다시 버튼을 누르면 자연스럽게 다시 접히며 사라지는 인터랙션입니다.

특히 이번 예제는 자바스크립트에서 CSS의 width나 left 값을 직접 복잡하게 제어하는 방식이 아니라, 클래스 이름을 스위치처럼 활용하는 classList.toggle() 메서드를 사용해 구현되어 있습니다. 이를 통해 실무에서 가장 많이 쓰이는 구조에 가깝고 깔끔한 방식으로 설계할 수 있습니다.

이 방식은 코드 가독성과 유지보수성을 높여주기 때문에 실제 프로젝트에서도 매우 자주 활용되는 패턴입니다.

또한 화면 공간을 효율적으로 사용하는 레이아웃 구조를 이해할 때 반드시 거쳐야 하는 기본적인 학습 과정이기도 합니다.

이 기능이 자연스럽게 동작하려면 이전의 ‘오버레이 메뉴’ 예제와 마찬가지로 CSS의 역할이 핵심입니다. 단순히 열리고 닫히는 것이 아니라, 유기적인 움직임과 전환 효과가 함께 적용되어야 완성도 높은 UI가 됩니다.

 


 

[자바스크립트 스위치와 CSS의 마법]

이번 예제에서 자바스크립트가 수행하는 역할은 매우 단순합니다. #sidebar 요소에 .act라는 클래스 이름을 붙였다가 제거하는 스위치 역할만 담당합니다.

실제 화면에서 보이는 애니메이션과 움직임은 전부 CSS가 처리합니다. 즉, 자바스크립트는 “상태를 바꾸는 역할”, CSS는 “움직임을 표현하는 역할”로 분리되어 있습니다.

  1. #sidebar 기본 스타일 (초기 상태)
    사이드바는 position: fixed;, top: 0;, left: -250px;, width: 250px;, transition: 0.4s;로 설정되어 있습니다.
    이 상태에서 사이드바는 자신의 너비만큼 왼쪽 화면 밖으로 밀려나 있어(left: -250px) 사용자에게 보이지 않게 대기합니다.

  2. #sidebar.act 상태 (활성화 상태) ★핵심
    자바스크립트가 .act 클래스를 추가하는 순간, left: 0; 스타일이 적용되며 사이드바가 화면 안쪽으로 들어옵니다.
    이때 기존에 설정된 transition: 0.4s; 덕분에 위치 변화가 즉시 반영되지 않고, 0.4초 동안 왼쪽에서 오른쪽으로 부드럽게 슬라이딩되며 등장하는 애니메이션이 완성됩니다.