have a javascript code below:
myBtn.addEventListener('click', () => {
current_candy++;
let previous_step = current_step - 1;
if(( current_candy > 0) && (current_candy <= stepCount)){
previous.classList.remove("d-none");
previous.classList.add("d-inline-block");
step[current_candy].classList.remove("d-none");
step[current_candy].classList.add("d-block");
step[current_candy].classList.remove("d-block");
step[previous_step].classList.add("d-none");
if (current_candy == stepCount){
submit.classList.remove("d-none");
submit.classList.add("d-inline-block");
next.classList.remove("d-inline-block");
next.classList.add("d-none");
}
} else {
if(current_candy > stepCount){
form.onsubmit = () => { return true }
}
}
});
As you can see that I am constantly adding and removing classes from this program.
Is there better way to do this? Is this a good practice?
current_stepandcurrent_candy? And could you tell us in words what the code is meant to do?classList.toggleis a method. Also thatclassList.addandclassList.removecan take multiple arguments. I can't see the point in adding and then removing the "d-block" class from the same object (unless one of yourcurrent_candyvariables should beprevious_step). But more importantly it's not really clear what you're trying to achieve overall. It's certainly fine to add/remove classes on click events.