Skip to content
Advertisement

How to alternate jquery toggle slide actions on click

I want to show two elements on click, one after the other, whereby a user clicks a button the first element with a class(.show-element-one), is shown and when the user clicks the same button for the second time the second element is shown with class(.show-element-two) , am using the code below to show element one on click but I am stuck with showing the second element on the second click.

jQuery(document).ready(function() {
  jQuery('#display-elements').click(function() {
    jQuery('.show-element-one,.show-element-two').toggle("slide");
  });
});

I will appreciate any guides, thanks.

Advertisement

Answer

You can set up a counter variable calculate the modulus value for that to display the element of that two classes in circular manner. Something like the code below:

jQuery(document).ready(function() {
  var count = 1;
  jQuery('#display-elements').click(function() {
    jQuery('.show-element-one, .show-element-two').hide();
    if (count % 2 !== 0) {
      jQuery('.show-element-one').toggle("slide");
    } else {
      jQuery('.show-element-two').toggle("slide");
    }
    count++;
  });
});
.show-element-one,
.show-element-two {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="display-elements"> Click me </button>
<div class="show-element-one">
  show-element-one
</div>
<div class="show-element-two">show-element-two </div>
Advertisement