Reputation:
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?
Upvotes: 0
Views: 46
Reputation: 18116
You can use toggle instead of add/remove classes, it returns true if the class was added, and false if it was removed.
for example:
submit.classList.toggle('d-block');
Check out w3schools example:
https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_toggle_class
Upvotes: 1