简体   繁体   中英

Jquery submenu accordion closes and opens upon click

i have hamburger menu, which i've done an accordion type submenu using jquery. Though it's only for devices which are 1084px and smaller. Otherwise the menu uses a hover style submenu on desktop.

Though for some reason, using both of these techniques (hover using css, and the accordion using jquery) is not working. So i had resulted in adding media queries to the jquery, which had allowed the hover and accordion to work.

BUT

Once the accordion is pressed, it opens and closes multiple times by itself, which is wrong and therefore not functioning properly. Can anyone help me out please, this problem only happens once i add the media query to my Jquery.

  jQuery(document).ready(function($) {

    $(window).resize(function() {
      if ($(window).width() < 500) {
        function initMenu() {
          $('#nav ul').hide();
          $('#nav li a').click(
            function() {
              var checkElement = $(this).next();
              if ((checkElement.is('ul')) && (checkElement.is(':visible'))) {
                $('#nav ul:visible').slideToggle('normal');
              }
              if ((checkElement.is('ul')) && (!checkElement.is(':visible'))) {
                removeActiveClassFromAll();
                $(this).addClass("active");
                $('#nav ul:visible').slideToggle('normal');
                checkElement.slideToggle('normal');
                return false;
              }
              if ($(this).siblings('ul').length == 0 && $(this).parent().parent().attr('id') == 'nav') {
                removeActiveClassFromAll();
                $(this).addClass("active");
                $('#nav ul:visible').slideToggle('normal');
                return false;
              }
            }
          );
        }

        function removeActiveClassFromAll() {
          $('#nav li a').each(function(index) {
            $(this).removeClass("active");
          });
        }
        $(document).ready(function() {
          initMenu();
        });
        $('#nav').click(function(e) {
          e.stopPropagation();
        })
        $(document).click(function() {
          $('#nav').children('li').each(function() {
            if ($(this).children('ul').css('display') == 'block') {
              $(this).children('ul').slideToggle('normal')
              $(this).children('a').removeClass('active')
            }
          })
        })

      }

    });

  });

here is a jsfiddle https://jsfiddle.net/kjm58tah/

thank you in advance

if (window.matchMedia("(max-width: 500px)").matches) {

}

this will work, however you need to refresh the page to make it work..

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