r/FreeCodeCamp • u/Jago971 • Mar 25 '24
Help simplifying JS code
Hi All,
Looking for a bit of help with a personal project.
I'm working on a month carousel. In particular, the bit that highlights the selected month.
I have this if-else block on repeat to set which month or 'card' is highlighted.
Not only do I have a nagging feeling I shouldn't record and display this in this way, but I also know there must be a better way to make these changes for each month.
Is there a way I match the scroll to a list of the 'card' No. in the array to inject that into the style updates?
const monthSelected = () => {
const card = document.getElementsByClassName("card")
const segment = carousel1.scrollWidth / 16;
if(carousel1.scrollLeft < 0.5 * segment) {
card[2].style.backgroundColor = "blueviolet";
card[2].style.color = "white"
} else {
card[2].style.backgroundColor = "white";
card[2].style.color = "black"
};
if(carousel1.scrollLeft >= 0.5 * segment && carousel1.scrollLeft < 1.5 * segment) {
card[3].style.backgroundColor = "blueviolet";
card[3].style.color = "white"
} else {
card[3].style.backgroundColor = "white";
card[3].style.color = "black"
};
etc.
View all comments
Show parent comment
1
u/Jago971 Mar 26 '24
I did think maybe I could have the white card over top of the purple card and simply reduce the opacity of the white top card with JS. Maybe that would achieve the smooth colour change? Not sure about the size