Skip to content
Advertisement

Buttons act weird due to .classList.toggle

I have a menu with some arrow buttons. If you click on those arrow buttons, one more div appears.

It’s working fine – but I noticed something strange. If I press on the right arrow 9 times (until all the 10 divs are shown), on the left arrow 9 times (until only the first div is shown) and then try to press on the right arrow 9 times (so all 10 divs are shown again) the menu gets stuck at the 8th div and I don’t understand why.

Is anything wrong with my code?

JavaScript
JavaScript
JavaScript

Why is this happening?

Advertisement

Answer

  1. When you are decrementing classCounter from 10, your function starts with classCounter– so it’s hiding 9th element not 10th.
  2. When you get to classCounter = 1, again your function starts with increment so it’s adding a second element not 1st.
  3. Increment to 10 again and you don’t have 1st (2.) element and 10th (1.) because you are toogling class on an element that is already visible.

In short you should rethink where classCounter++ and classCounter– should be.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement