Home > Net >  Issue with backward and forward to change colors in JavaScript
Issue with backward and forward to change colors in JavaScript

Time:10-06

i am having this problem when i try to change colors in my small app. But first, i am trying to make a small app to generate random colors and save them to be able to use a backward and forward button.

I'll put a link to codepen if you want to see it in action and understand it way better.

Link: random colors app

My problem: after generating two colors and i click backward i get the same color (Yes, i know that i'm using a .pop() method to get current color), and i have to click it twice to see the change.

So, my question. Should I use another "logic" to get my colors instead of .pop() and .push() methods?

I'll appreciate all the help!

CodePudding user response:

Here's why you're having this issue! Took me a little to figure it out...

When you generate a new color, you're immediately setting the new color as your current color. And what happens after? You're pushing it to the backwardStack array!

This means that when you turn RED, then GREEN...

  1. Generate RED, set as current color, then immediately push RED to backward stack

  2. Generate GREEN, set as current color, then immediately push GREEN to backward stack

Backward should only be available once at least 1 color has passed, not immediately upon adding a color. Meaning that you should...

  // Reverse the order of these actions!

  // Action 1
  changeColor(hexColor);
  currentColor = hexColor;
  console.log("Current color: "   currentColor);

  // Action 2
  if (currentColor) {
    backwardStack.push(currentColor);
  }

  //----------------------

  // Action 2
  if (currentColor) {
    backwardStack.push(currentColor);
  }

  // Action 1
  changeColor(hexColor);
  currentColor = hexColor;
  console.log("Current color: "   currentColor);

Which basically says:

Before I set a current color, do I have a current color? If yes, push to the backwardStack. If I have no current color, don't push to the backwardStack and still set my current color. That means on the first color generate, the backward button should not become clickable.

This is also the reason why every time you generate a color, the backward button has to then be pushed twice!

Hopefully this helps.

  • Related