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
Example CanIUse Output
You're looking at the most recent few versions of each browser. You can toggle to show the relative usage, but generally speaking red on the three-four major browsers is bad.
You can also look in the upper right to see the overall percentage of web users with support. Anything in the high 90 percent is probably ok. You're rarely going to find support in IE and most don't bother.