ハンバーガーメニューを実装する【JavaScript・CSS】
記事内に商品プロモーションを含む場合があります
クリックするとハンバーガーメニューが✗に変化するアニメーションサンプルです。
ハンバーガーメニューの実装
ハンバーガーメニューをクリックすることで、id「js-menu」内を表示非表示を切り替えます。
HTML
<div class="header-btn"> <button id="menu-trigger" class="menu" aria-label="メニュー"> <span></span> <span></span> <span></span> </button> </div> <nav id="js-menu"></nav>
CSSでアニメーションを実装
.header-btn {
width: 35px;
height: 25px;
position: relative;
z-index: 13;
}
.menu {
display: block;
transition: all .4s;
width: 100%;
height: 100%;
background: none;
border: none;
appearance: none;
cursor: pointer;
span {
display: inline-block;
transition: all .4s;
position: absolute;
left: 0;
width: 100%;
height: 3px;
background-color: #00aac3;
&:nth-of-type(1) {
top: 0;
}
&:nth-of-type(2) {
top: 11px;
}
&:nth-of-type(3) {
bottom: 0;
}
}
&.active {
span {
&:nth-of-type(1) {
top: 50%;
transform: translateY(-50%) rotate(-45deg);
}
&:nth-of-type(2) {
top: 50%;
transform: translateY(-50%) rotate(45deg);
}
&:nth-of-type(3) {
opacity: 0;
}
}
}
}
JavaScriptでclassを追加
function headerMenu() {
document.getElementById("menu-trigger").addEventListener("click", function () {
let menu = document.getElementById('js-menu');
menu.style.display = (menu.style.display === 'none' || menu.style.display === '') ? 'block' : 'none';
this.classList.toggle('active');
});
let menuLinks = document.querySelectorAll(".menu a");
menuLinks.forEach(function (link) {
link.addEventListener("click", function () {
let menu = document.getElementById('js-menu');
menu.style.display = 'none';
document.getElementById("menu-trigger").classList.toggle('active');
});
});
}
document.addEventListener("DOMContentLoaded", function () {
headerMenu();
});
ABOUT ME