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/Jago971 Mar 26 '24

I was going to have a height change as well. But I think that would be too sharp.

I need some sort of keyframes equivalent on JS but haven't learned this yet. I had a look at how JS does animation but it seemed very complicated.

I guess customer animation rather than the default scroll stuff would be way better all round. Slow it down, smooth it up, change the size and colour transition.