Bilal Khalid
Bilal Khalid

Reputation: 23

Clicking multiple times on a show/hide function in jQuery

I made this something like this:
Codepen or code down.

$(document).ready(function () {
  var btn1Status = 0;
  $("button").click(function () {
    if (btn1Status === 0) {
      $(".info").slideDown();
      $(".info").show("slow");
      $("button").text("less");
      btn1Status = 1;
    } else {
      $(".info").slideUp();
      $(".nfo").hide("slow");
      btn1Status = 0;
      $("button").text("More");
    }

  });
  });
button {
  background-color: black;
  color: white;
  width: 50px;
  height: 30px;
}
button:focus {
  outline: none;
}
ul {
  list-style-type: none;
  margin: 10px;
  padding: 0;
}

.info {
  background-color: black;
  color: white;
  font-family: arial;
  width: 400px;
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<div><img src="https://img.favpng.com/22/6/0/portable-network-graphics-movie-camera-film-clip-art-computer-icons-png-favpng-qfZ7hHPN2CCxiK8sYfjS2Sti9.jpg" width="400"><button>More</button></div>

<div class="info">
  <ul>
    <li>Name: movie1</li>
    <li>Time: 6:00PM</li>
    <li>Info 3 : blablabla</li>
    <li>Info 4 : blablabla</li>               
    </ul>
</div>

when someone clicks the button, the info div should appear. the problem is, if I click the button multiple times then lift it, it will keep showing and disappearing. How do I fix this problem. Thanks for helping.

Upvotes: 0

Views: 468

Answers (1)

Keith Brewster
Keith Brewster

Reputation: 3652

If you want the ability to let the users click multiple times but not build a queue of animations you can use the stop function from jQuery to stop/clear the queue of any currently running animations.

if (btn1Status === 0) {
  $(".info").stop(true, true).slideDown();
  $(".info").show("slow");
  $("button").text("less");
  btn1Status = 1;
} else {
  $(".info").stop(true, true).slideUp();
  $(".info").hide("slow");
  btn1Status = 0;
  $("button").text("More");
}

This will cancel the queue of animations if the button is clicked multiple times. The two arguments of .stop() are: ( [clearQueue ] [, jumpToEnd ] ). clearQueue is needed to clear the current animation queue, jumpToEnd will either cancel the currently running animation before jumping to the next one, or begin running the next slide animation from the current animation frame.

Upvotes: 1

Related Questions