Search code examples
jqueryhtmlslidetoggleslidedownslideup

How to make proper jQuery slide down menu ?


Hello friends!

I'm having issue with slide down menu when I initially click on button(image) which is <a id="js-cat" class="js-cat"></a> it works, but it slides down and immediately slides up again, which I haven't planned to do. My goal is to make it responsive, for instance; if user gonna click that button(image) once it should slide down, and if user gonna click it twice and it should slide up again.

Please guys I need your help. I was hardly trying to do it, but it eventually I'm unable to make my code work.

Here is my HTML:

<a id='js-mnu' class='js-mnu'></a>
<a id="js-cat" class="js-cat"></a>

CSS

#js-cat {display:block;display:block;width:35px;height:35px;margin:17px  10px; position: absolute;
right: 0;}
.js-cat {background:url(images/cat.png) center center no-repeat;opacity:0.75;}

And jQuery:

$(document).ready(function(){
  $("#js-cat").click(function(){
       $('ul.catalog').slideDown();
    });
  $("#js-cat").click(function(){
       $('ul.catalog').slideUp();
    });
});

Solution

  • You are binding the click event twice. You should only bind it once and check if the menu is hidden or not to slideup or down.

    $(document).ready(function() {
      $("#js-cat").click(function() {
        var isHidden = $(".menu").is(":hidden");
        if (isHidden) {
          $('.menu').slideDown();
        } else {
          $('.menu').slideUp();
        }
      });
    
    
    });
    body {
      margin: 10px;
    }
    
    .menu {
      margin: 10px 0;
      background: #abcdef;
      width: 250px;
      padding: 10px;
    }
    
    a {
      cursor: pointer;
      border: 1px solid #555;
      background: #fafafa;
      color: #555;
      padding: 10px;
      display: inline-block
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <a id="js-cat" class="js-cat">Click</a>
    
    <div class="menu">Content: Lorem ipsum</div>