简体   繁体   中英

interactive menu can't slide back in Jquery

I was trying to make an interactive menu. It should work like this:

  1. If I click on menu-icon the navigation will slide down to visible area (It works)
  2. Then If I click menu-icon again the navigation will return back to invisible area again. But the second step doesn't work.

     $(document).ready(function(){ $(".menu-icon").click(function(){ $("#navigation").animate({top: "40%"}),5000; $(this).addClass("menu-icon-active").removeClass("menu-icon"); }); $(".menu-icon-active").click(function(){ $("#navigation").animate({top: "-40%"}),5000; $(this).addClass("menu-icon").removeClass("menu-icon-active"); }); 

    });

Have got somebody an idea how to make it?

You can solve your problem by checking within the same click hander if the element has the "active" class, and if so, deactive it, and if not "activate" it.

Here is a working code sample:

$(document).ready(function() {

    $(".menu-icon").click(function() {

        if ($(this).hasClass("menu-icon-active") ){

            // menu is active, deactivate it
             $("#navigation").animate({
                top: "10%"
            }), 5000;

            $(this).removeClass("menu-icon-active");

        } else {

            // menu is not active
            $("#navigation").animate({
                top: "30%"
            }), 5000;

            $(this).addClass("menu-icon-active");

        } 

    });
});

CLICK HERE TO SEE A FIDDLE OF THIS CODE IN ACTION

Hope this helps!

UPDATE: jQuery Tip: There is no need for you to add or remove the menu-icon class from within your menu-icon click handler. That is not needed and will probably give you unexpected or erroneous results. [Thanks to the user @TJ for pointing that out.]

I know this is already solved but FYI jQuery has slideToggle() and toggleClass() methods for exactly this sort of thing:

 $(function(){ $("#navigation").hide();//initially hidden $(".menu-icon").on("click",function(){ $("#navigation").slideToggle(); $(this).toggleClass('active'); }) }) 
 .active {color:green} 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <a href="#navigation" class="menu-icon">click me</a> <ul id="navigation"> <li>item</li> <li>item</li> <li>item</li> <li>item</li> </ul> 

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