0

I'm making an image slideshow, where 3 images have their CSS classes switched .onClick() so that they rotate position.

.flip-1 becomes .flip-2 
.flip-2 becomes .flip-3
.flip-3 becomes .flip-1

Problem: my JQuery runs too fast, and I think recursively so every image ends up with the class .flip-1 in element inspect.

My JQuery is this:

        $(document).ready(function () {
          $('.ebook--flip').click(function() {
              $('.flip-1').removeClass('flip-1').addClass('flip-2');
              $('.flip-2').removeClass('flip-2').addClass('flip-3');
              $('.flip-3').removeClass('flip-3').addClass('flip-1');
          });
    });

I was Googling around and think I could use delays, but is there a way to just run the remove/add class functions in sequence and stop at the end?

Once per click?

4
  • .removeClass() and addClass() are instantaneous... And .delay() only has effect on jQuery animations. You probably have to use setTimeout(). Commented Jul 24, 2018 at 23:42
  • What does 'in sequence' mean? After each click or after a certain amount of time passes? Commented Jul 24, 2018 at 23:43
  • @Karl for each and every click, I'd like each of the $('.flip-x') lines to run once. One, then the other. Commented Jul 24, 2018 at 23:47
  • I would suggest checking for the current class applied to .ebook--flip on each click and then change the class to the next in series. This would prevent the issue of it being dependent on time and all happening at once. Commented Jul 24, 2018 at 23:51

1 Answer 1

2

Try this:

$(document).ready(function () {
      $('.ebook--flip').click(function() {
          var $flip1 = $('.flip-1');
          var $flip2 = $('.flip-2');
          var $flip3 = $('.flip-3');

          $flip1.removeClass('flip-1');
          $flip2.removeClass('flip-2');
          $flip3.removeClass('flip-3');

          $flip1.addClass('flip-2');
          $flip2.addClass('flip-3');
          $flip3.addClass('flip-1');
      });
});

The problem is that every time you change the class to an image you are affecting the next line of your code.

For example:

  1. flip-1 changes to flip-2
  2. $('flip-2') captures former flip-1 and the original flip-2, and change them to flip-3
  3. $('flip-3') captures former flip-1, flip-2 and flip3 and change them to flip-1.

Finally, all your images end up with the flip-1 class applied.

Hope this helps.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.