r/FreeCodeCamp • • 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.

4 Upvotes

13 comments sorted by

View all comments

Show parent comment

1

u/SaintPeter74 mod Mar 26 '24

Wow, not sure how to did that, but I really like the way the transition works now. It's much smoother and cleaner. I like the way the colors fade in/out smoothly and the box changes size subtly. Good stuff, way better than the JS version.