Could someone take a look at this codepen https://codepen.io/huereca17/pen/jJzbev?editors=1011 and explain how I can reset my index value back to zero? When I reach the end of the array I would like to restart back to the beginning of the array. I have been on this for the past two days
I think it’s pretty comprehensive in terms of pseudo-code. I guess I could make it more specific by splitting it into the two functions:
nextFunction
Increment index.
Check if new value of index is colors.length.
If yes, set index to min (0).
Else, do nothing.
Set color based on new value of index.
previousFunction
Decrement index.
Check if new value of index is -1.
If yes, set index to max (colors.length - 1).
Else, do nothing.
Set color based on new value of index.
Note that step 3 is identical in both cases, so you may want to split it into its own function. You could also run this function on page load, so that your #display is initially set to the first color in the array.
Why does my next(or prev) button decrements before it actually increments the other way on this color slide show? I can’t figure it out and it’s driving me crazy.
@silashuereca If you add “prev” and “next” ids to the buttons and pass the id names to a single function (i.e. changeColor), you could do something like the following:
let display = document.getElementById("display");
let colors = ["red", "green", "blue", "orange"];
let index = 0;
function setBackgroundColor (color) {
display.style.backgroundColor = color;
}
function changeColor (direction) {
index += (direction === 'next' ? 1 : -1);
if (index < 0) {
index = colors.length - 1;
}
else if (index === colors.length) {
index = 0;
}
setBackgroundColor(colors[index]);
}
setBackgroundColor(colors[index]);
I added another helper function just to clean up setting the background. Plus I specified the background to the first color “red” when the page first loads instead of the background being white.
I just want to say thank you for your contribution to my project. This solution really helped me understand a better logic with JS code. I really appreciate it.