I'd appreciate some help with this. I have two questions. Here's the first question:
For some reason, I can't get the classlist.remove to work when I want to clear a class from an element before I add another. I'm trying to make a slideshow feature and whenever a user clicks an arrow a class is applied which makes the element appear to be sliding (from left, or right depending on what button was clicked).
I'm trying to do this be first removing the additional classes (slidein/slideinleft) so that I can add them and reapply the feature. Any ideas why it doesn't seem to be working? (note, it only works the first time you press a button, I want it to work every time)
And here are the codes:
function addclass(i, c) {
document.getElementById(i).classList.remove("slidein", "slideinleft");
document.getElementById(i).classList.add(c);
}
/* Slideshow container */
.slideshow-container {
margin: 0;
max-width: 80%;
overflow: hidden;
}
.slides {
position:relative;
width:80%;
margin: 0;
background:red;
}
/* Next & previous buttons */
.prev, .next {
font-family: Verdana;
opacity: 0.4;
cursor: pointer;
position: absolute;
top: 0%;
font-size: 28px;
transition: 0.6s ease;
user-select: none;
font-weight: bold;
padding-left: 2%;
-webkit-filter: grayscale(100%); /* Safari 6.0 - 9.0 */
filter: grayscale(100%);
}
/* Position the "next button" to the right */
.next {
left: 90%;
}
.prev {
right: 90%;
}
.prev, .next:hover {
opacity: 1;
-webkit-filter: none; /* Safari 6.0 - 9.0 */
filter: none;
}
.slidein {
animation-name: slidein;
animation-duration: 1.5s;
}
@keyframes slidein {
from {left: 100%}
to {left: 0}
}
.slideinleft {
animation-name: slideinl;
animation-duration: 1.5s;
}
@keyframes slideinl {
from {right: 100%}
to {right: 0}
}
<center><div class='slideshow-container'>
<table id='curt1' class='slides'>
<tr>
<td>#1</td>
</tr>
</table>
</div>
</center>
<div class='next' onclick='addclass("curt1", "slidein")'>❯</div>
<div class='prev' onclick='addclass("curt1", "slideinleft")'>❮</div>
My second question, is what if I wanted to achieve the same thing without using id:s. I've isolated the relevant codes in my example above. But really I'm sliding between several elements that have the same class, and are not specified with any id. Is it possible or will I need to edit my codes so that I give each element an id?
Many thanks in advance for your professional guidance!
After being referred to this thread I solved the problem by using solution #4. I changed the function to this:
function addclass(i, c) {
document.getElementById(i).classList.remove(c);
document.getElementById(i).classList.remove("slidein");
document.getElementById(i).classList.remove("slideinleft");
void document.getElementById(i).offsetWidth;
document.getElementById(i).classList.add(c);
}