简体   繁体   中英

JavaScript Toggle Show/Hide Responsive Menu

I've been stuck on this particular problem. I would like to use a toggle menu for mobile widths on a website that I'm working on. Basically, it works nicely as I can show you on this CodePen .

The code for showing/hiding the menu via a toggle button with JavaScript works below.

$(document).ready(function() {

  //Menu Open Seasame Action    
  $('.site-nav-btn').click(function() {
  $('.site-nav ul').slideToggle('fast');
  $(this).find('span:hidden').show().siblings().hide();
});

  //Hide site-nav content.    
  $(".site-nav ul").hide();
});

My problem is that I would like to hide the toggle button and the toggle function when the width exceeds say, 480 pixels wide but keep the site-nav ul visible. I've been trying to do this via this code combined with the one above, and somehow it just doesn't work.

$(function() {
  if ($(window).width() > 480) {
      $('.site-nav-btn').css('display','none');
      $('.site-nav ul').show();
      }
  else {
      $('.site-nav-btn').css('display','block');
      $('.site-nav ul').hide();
      }
  });

I'm not really that proficient in JavaScript so if anyone could point out why it didn't work alongside the solutions that would really be helpful.

Attach your checking function to $(window).resize() and fix the selectors. See this fork of your CodePen .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM