0

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?

3
  • What's the relationship between current_step and current_candy? And could you tell us in words what the code is meant to do? Commented Apr 14, 2021 at 11:35
  • Well…if you’re using class name to keep track of some kind of “state”, you need sth to save that state anyway. I don’t know what purpose your class name serves, all I can say is, this is normal practice. Commented Apr 14, 2021 at 11:38
  • It might help to know that classList.toggle is a method. Also that classList.add and classList.remove can 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 your current_candy variables should be previous_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. Commented Apr 14, 2021 at 11:39

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.