Search code examples
javascriptjquerydropdownslidetoggledropdownbox

slideUp and slideDown animation does not work after first use


I have used jQuery to build something like a dropdown, but it only works for the first two clicks, and then it doesn't. How can I make a dropdown? Can it be done with a loop? (I have not learnt loop yet, so any solution would work.)

For Each SLIDEUP and SLIDEDOWN I wanted to make different TIME....

jQuery(document).ready(function() {
  jQuery(".click-on").click(function() {
    jQuery(".box").slideUp(2000, function() {
      jQuery(".click-on").click(function() {
        jQuery(".box").slideDown(500);
      });
      return false;
    });
    return false;
  });
});
.box {
  width: 300px;
  height: 300px;
  background-color: skyblue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p id="fan">THIS IS A FAN</p>
<p id="gun">THIS IS A GUN</p>

<p class="click-on">Click Here</p>
<div class="box"></div>


Solution

  • This is because you misunderstand the meaning of the .click() function.

    .click() sets the handler function each time when the click event is triggered from the selected DOM.

    Since you have called another .click() within the callback of .slideUp(), you are actually replacing the handler function. In your current logic, the obvious fix is to do infinite callback after each click like:

    jQuery(".click-on").click(function(){
        jQuery(".box").slideUp(2000, function(){
            jQuery(".click-on").click(function(){
                jQuery(".box").slideDown(500,function(){
                    jQuery(".click-on").click(function(){ 
                        jQuery(".box").slideUp(2000, function(){//Repeating callbacks... ...
                });
            });
        });
    });
    

    and seriously it is very bad. Such implementation should not be done.

    Instead, it is better for you to have a conditional checking for each click, so the logic will determine itself either .slideUp() or .slideDown() should be called. It should be like

    $(".click-on").click(function(){//you can also use $ instead of jQuery
        //do some conditional check here
        if(isSlidedUp)$(".box").slideDown(1000);
        else $(".box").slideUp(1000)
    });
    

    or even better you use .slideToogle().

    $(".click-on").click(function(){
        $(".box").slideToggle(1000)
    }