今回はよく使うハンバーガーメニューをJQueryからJavaScriptへ書き変えました。
ハンバーガーメニューが開いている時は、bodyに「is-nav-opened」のclassを付与しています。
下準備
まずhtml
<div class="p-hamburger js-hamburger"> <span class="p-hamburger__bar"> <span></span> <span></span> <span></span> </span></div>HTML次にcss(今回はscssで書きました)
$color-key: #0d95cb;.p-hamburger { cursor: pointer; &__bar { position: relative; display: block; width: 24px; height: 18px; > span { display: inline-block; position: absolute; left: 0; width: 100%; height: 2px; background-color: $color-key; transition: .35s; &:nth-of-type(1) { top: 0; } &:nth-of-type(2) { top: 8px; } &:nth-of-type(3) { bottom: 0; } .is-active & { &:nth-of-type(1) { transform: translateY(8px) rotate(-405deg); } &:nth-of-type(2) { opacity: 0; } &:nth-of-type(3) { transform: translateY(-8px) rotate(405deg); } } } }}SCSSJQueryでハンバーガーメニューを実装する場合
var trigger = $('.js-hamburger');var body = $('body');trigger.on('click', function() { if ($(this).hasClass('is-active')) { $(this).removeClass('is-active'); body.removeClass('is-nav-opened'); } else { $(this).addClass('is-active'); body.addClass('is-nav-opened'); }});JavaScriptサンプル
JavaScriptでハンバーガーメニューを実装する場合
var trigger = document.querySelector('.js-hamburger');var body = document.querySelector('body'); trigger.addEventListener('click', function () { if( this.classList.contains('is-active')) { this.classList.remove('is-active'); body.classList.remove('is-nav-opened'); } else { this.classList.add('is-active'); body.classList.add('is-nav-opened'); }});JavaScript