Class toggle when div ID == var
Hey front-enders!
I’ve been building a carousel with some snippets of JS and CSS, where 'var curSlide' returns the index of the current slide.
My next goal is to reveal different text elements inside of a div that is adjacent to the slider (so that they don’t follow the movement of the carousel.
Now I want to show/hide the text element, have assigned them with IDs that are identical to each slide index, and want to run an if-statement to send the correct css class to corresponding IDs.
I’ve kind of "sketched" it in my head, but my JS knowledge is more or less non-existent, so obviously it doesn’t work 🤣
Any pointers on how to do this is much appreciated!
if (document.getElementById(" ") == curSlide) {
e.target.classList.add("text__show");
} else {
e.target.classlist.add("text__hidden");
}
4 Replies
Instead of a truck-load of
if
and else if
statements, let me introduce you to the switch
statement!
It evaluates an expression and executes the code that matches the eval:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switchThis works amazingly. Thank you!
A short follow-up though, as some carousels will have 'x' amount of slides and others 'y' amount, and it feels superfluous to have to write out all potential scenarios. Currently I have the following running when clicking next-button and a reversed order on previous.
I don’t know if it is allowed in JS, but in my head I’m thinking: Can this be simplified by injecting the var into the ID?
can you show html?
that logic in switch statement is strange
Too long to paste it here, but slapped it up here: https://codepen.io/sebreed/pen/yLReWNo
Transitions are breaking because they link to my base.css, but otherwise the functionality is working.