[JavaScript] 스크롤 반응형 메뉴바

HTML

1
<div id="header"></div>

CSS

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
body {
    height: 2000px;
}
#header {
    position: fixed;
    top: 0;
    left: 0;
    background: salmon;
    width: 100%;
    height: 100px;
    transition: top 0.5s;
}
#header.hide {
    top: -100%;
}

JavaScript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
var lastScrollTop = 0;
var headerHeight = $("#header").outerHeight();

$(window).scroll(function() {
    var scrollTop = $(this).scrollTop();

    if (scrollTop > lastScrollTop && scrollTop > headerHeight) {
        $("#header").addClass("hide");
    } else {
        $("#header").removeClass("hide");
    }

    lastScrollTop = scrollTop;
});

결과확인

See the Pen 스크롤 반응형 메뉴바 by 이지연 (@jiyeonjyn) on CodePen.