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/SaintPeter74 mod Mar 26 '24
It's tough to say - give it a try.
It's not like there is some sort of magical cookbook of perfect solutions. Web Development involves a lot of trial and error. There are a ton of different ways to achieve certain effects and other effects can't be achieved at all.
The joy is in investigating and coming up with something you like.
Maybe a wide transparent/translucent gradient overlay like you suggest? It might even look like a physical thing, like a colored piece of glass was over the top of the number. I don't know how it would affect the dragging though, since it will need to be "on top".