Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

257
Views
Issue with backward and forward to change colors in JavaScript

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!

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!