見出し画像

【jQuery】要素外をクリックで閉じるメニュー雛形

HTML

<body>
   <button class="open"></button>
   <div id="menu">
   <div class="menuWrapper">
       <button class="close"></button>
       <div class="content">
           <p>メニュー内のコンテンツ</p>
       </div>
   </div>
</div>
</body>

CSS

button.open {
   width: 56px;
   height: 56px;
}

#menu {
   display: none;
   /* display: flex; */
   justify-content: center;
   align-items: center;
   position: fixed;
   top: 0;
   left: 0;
   width: 100%;
   height: 100%;
   background: rgba(0, 0, 0, 0.5);
}
#menu .menuWrapper {
   position: relative;
   display: flex;
   justify-content: center;
   align-items: center;
   width: 750px;
   height: 80%;
   background: #ffffff;
}
#menu .menuWrapper button.close {
   position: absolute;
   top: 0;
   right: 0;
   width: 56px;
   height: 56px;
}

jQuery

return false; でメニューを開くときに
cssメソッド→クリック判別 となり、fadeOutが作動してしまうのを回避しているので注意。

$(function(){
   $(document).on('click touchend', function (event) {
       if (!$(event.target).closest('.menuWrapper').length && ($('#menu').css('display') == 'flex')) {
           $('#menu').fadeOut();
       }
   });
   $('button.open').click(function(){
       $('#menu').fadeIn().css('display','flex');
       return false;
   });
   $('button.close').click(function(){
       $('#menu').fadeOut();
       return false;
   });
});

この記事が気に入ったらサポートをしてみませんか?