简体   繁体   中英

jQuery accordion menu - trouble hiding submenus by default

I'm trying to create a jQuery accordion-style menu and I've very nearly got it working but I've been stuck for hours trying to work out why the submenus are showing by default when the page loads.

I've tried hiding them using CSS and for some reason they then won't slide down at all. I've also tried hiding them in the jQuery and have the same problem.

I've obviously gone wrong somewhere but I can't work out where.

I've created a JSFiddle for the HTML and CSS: http://jsfiddle.net/rcord/Gd7DM/7/

My jQuery is:

    $(document).ready(function () {
      $('#mobnav > ul > li > a').click(function () {
        $('#mobnav li').removeClass('active');
        $(this).closest('li').addClass('active');
        var checkElement = $(this).next();
        if ((checkElement.is('ul')) && (checkElement.is(':visible'))) {
        $(this).closest('li').removeClass('active');
        checkElement.slideToggle('normal');
      }
      if ((checkElement.is('ul')) && (!checkElement.is(':visible'))) {
        $('#mobnav ul ul:visible').slideToggle('normal');
        checkElement.slideToggle('normal');
      }
      if ($(this).closest('li').find('ul').children().length === 0) {
        return true;
      } else {
        return false;
      }
     });
    });

Thank you!

edit: Thank you very much to the two people who've answered - that works perfectly. I'm new to stackoverflow and I'm not sure where I'm supposed to say thank you since it says not to use comments...

Change your menu selector from nav ul to #mobnav > ul otherwise you're toggling all lists inside the nav with the first click

$(function () {
    var pull = $('#pull');
    menu = $('#mobnav > ul');
    $(menu).on('load').hide();
    menuHeight = menu.height();
    $(pull).on('click', function (e) {
        e.preventDefault();
        menu.slideToggle();
    });
...
});

Updated fiddle

Your top navigation selector menu = $('nav ul'); is selecting all the ul elements, change it to `#mobnav > ul instead

var pull = $('#pull');
menu = $('#mobnav > ul');
$(menu).on('load').hide();
menuHeight = menu.height();
$(pull).on('click', function (e) {
    console.log('p')
    e.preventDefault();
    menu.slideToggle();
});

Demo: Fiddle

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