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:
JavaScript
x
14
14
1
<div class="steps">
2
<div class="step" id="0"></div>
3
<div class="step" id="1"></div>
4
<div class="step" id="2"></div>
5
<div class="step" id="3"></div>
6
<div class="step" id="4"></div>
7
<div class="step" id="5"></div>
8
<div class="step" id="6"></div>
9
<div class="step" id="7"></div>
10
<div class="step" id="8"></div>
11
<div class="step" id="9"></div>
12
<div class="step" id="10"></div>
13
</div>
14
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:
JavaScript
1
2
1
progress(x.target.id);
2
Replace by:
JavaScript
1
2
1
progress(+x.target.id);
2
And on lines, 14, 18 and 21, do the same.
JavaScript
1
13
13
1
steps.forEach((e) => {
2
if (+e.id === stepNum) { // <-- here
3
e.classList.add('selected');
4
e.classList.remove('completed');
5
}
6
if (+e.id < stepNum) { // <-- here
7
e.classList.add('completed');
8
}
9
if (+e.id > stepNum) { // <-- and here
10
e.classList.remove('selected', 'completed');
11
}
12
});
13
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.