简体   繁体   中英

Drop down menu- how to reverse animation on second click of a button?

I am trying to make a drop down menu using jQuery.

This is my HTML:

<div class="overlaydiv">This is my menu!</div>  

    <div class="row one">
      <div class="large-12 columns">



      </div>
    </div>


    <div class="row two">
      <div class="large-12 columns">

         <button id="b1">Drop down the menu!</button>   

      </div>
    </div>

CSS for overlay:

.overlaydiv { height: 100vh; width: 100vw; background-color: aquamarine; position: absolute; top: -100%; z-index: 1; }

This is jQuery that drops down the menu on click:

$("#b1").on("click", function() {

         $(".overlaydiv").animate({top: "0%"}, 200, 'swing');

      });

What would be the easiest way to reverse animation on second click?

The best way I can think of is using CSS transition.

So, here's the CSS:

.overlaydiv{ 
    height: 100vh; 
    width: 100vw; 
    background-color: aquamarine; 
    position: absolute; 
    top: -100%; 
    z-index: 1; 
    transition: all 0.2s;
}

.overlaydiv.active{
    top: 0%;
}

And the JS

$("#b1, .overlaydiv").on("click", function() {

     $(".overlaydiv").toggleClass("active");

});

You can check that to assign class active on your button and make action on it.

 $("#b1").on("click", function() { if($(this).hasClass("active")){ $(this).removeClass("active"); $(".overlaydiv").animate({top: "-100%"}, 200, 'swing'); }else{ $(this).addClass("active"); $(".overlaydiv").animate({top: "0%"}, 200, 'swing'); } }); 
 .overlaydiv { height: 100vh; width: 100vw; background-color: aquamarine; position: absolute; top: -100%; z-index: 1; } #b1 {position:relative;z-index:2} 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="overlaydiv">This is my menu!</div> <div class="row one"> <div class="large-12 columns"> </div> </div> <div class="row two"> <div class="large-12 columns"> <button id="b1">Drop down the menu!</button> </div> </div> 

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