NK Montreal
NK Montreal

Reputation: 41

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();
    });
});

Upvotes: 0

Views: 2550

Answers (2)

amir
amir

Reputation: 31

can't you just use Toggle ? i think with toggle u can get both slide down and slide up options on one button. remember to hide it with read(function()) at the begining.

Upvotes: 0

anpsmn
anpsmn

Reputation: 7257

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>

Upvotes: 1

Related Questions