Skip to content
Advertisement

Don’t understand why it only put the first int into array in javaScript

I would like to create a progress bar using Js. I’m following the online demo made by Cassidy Williams on September 13, 2018. Link: https://codepen.io/cassidoo/pen/wEXQaG

I added more steps into the steps div elements:

  <div class="steps">
    <div class="step" id="0"></div>
    <div class="step" id="1"></div>
    <div class="step" id="2"></div>
    <div class="step" id="3"></div>
    <div class="step" id="4"></div>
    <div class="step" id="5"></div>
    <div class="step" id="6"></div>
    <div class="step" id="7"></div>
    <div class="step" id="8"></div>
    <div class="step" id="9"></div>
    <div class="step" id="10"></div>
  </div>

But when I click the third step the last step status is clicked. What is the problem with this error? Also, what is the solution to this error?

Advertisement

Answer

On line 6 of the JS code, the author have the following:

progress(x.target.id);

Replace by:

progress(+x.target.id);

And on lines, 14, 18 and 21, do the same.

steps.forEach((e) => {
    if (+e.id === stepNum) { // <-- here
      e.classList.add('selected');
      e.classList.remove('completed');
    }
    if (+e.id < stepNum) { // <-- here
      e.classList.add('completed');
    }
    if (+e.id > stepNum) { // <-- and here
      e.classList.remove('selected', 'completed');
    }
});

The HTML id is a string, so a cast is necessary. The conditions misbehave because a string comparison is used instead of a number comparison. By casting the string to a number, it is working as intended.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement