How to get dropdown menu to open/close on click rather than hover?

后端 未结 5 1676
星月不相逢
星月不相逢 2021-02-06 07:32

I am very new to javascript and ajax/jquery and have been working on trying to get a script to open and close the drop menu on click rather that hover.

The menu in quest

5条回答
  •  醉话见心
    2021-02-06 08:16

    I would do something like this...

    $(function() {
     $("#lang-selector > li").click(function() {
         $('ul:first',this).toggleClass('active');
     });
    });
    

    And, then, in the CSS add this:

    .active { display: block; }
    

    << EDIT: Removed "ul" from ".active" class for CSS rendering efficiency >>

    Also make sure that the sub-nav

      has "display: none;" on it by default in your CSS.

      This will make it so that clicking an

    • tag in #lang-selector, but not in any sub-nav
        tags will either open or close the sub-nav, depending on it's current state.

        If you're worried about the accessibility of having "display: none" on the sub-nav by default, you can do something like this...

         $(function() {
          $("#lang-selector li ul").addClass("hidden");
          $("#lang-selector li").click(function(e) {
              e.preventDefault();
              $('ul:first',$(this)).toggleClass('hidden active');
            });
         });
        

        << EDIT: Altered selectors to match example provided, turned "this" into jQuery object. >>

        And then also add this to the CSS

        .hidden { display: none; }
        

        In this scenario, you have the

          showing by default, then when the document loads, jQuery adds the "hidden" class to all of them to hide them, then on the click of the
        • it will toggle the hidden and active classes, displaying them or hiding them.

          You'll also need to remove your current "display: none" from your #lang-selector ul ul in CSS, otherwise it takes priority over the hidden / active classes.

提交回复
热议问题