I made a progressbar using JavaScript and I later added a intersection observer API to let it automatically run.
I now want to have multiple of these progressbars in my website and my teachers at school told me I could better just copy the code multiple times and change the ID (which I disagree with but I do not know how to make multiple prgressbars run by 1 script).
I copied my html 2 times with a other ID-name and changed the ID-name in my JavaScript file and I even put it in a different <script>
section but only one progressbar works (the 1st one) the second one does not work.
Why doesn't it work? I am currently learning JavaScript so please tell me what I am doing wrong or if there is room for improvement besides my whole script not working for more then once...
my html =
div class="progressbars">
<div class="progress_status">
<div id="progressbar">
<p>5%</p>
</div>
</div>
</div>
<div class="progressbars">
<div class="progress_status">
<div id="progressbar2">
<p>5%</p>
</div>
</div>
the CSS for it ( don't think you will need it but just to be sure)
#progressbar /*,#progressbar2 ,#progressbar3 ,#progressbar4*/{
width: 5%;
height: 35px;
background-color: #D8135A;
text-align: center;
line-height: 32px;
color: white;
}
the JavaScript (the first one works, the second one does nothing to my second progressbar)
<script>
const progress = document.getElementById('progressbar')
const options = {
threshold : 1
};
let observer = new IntersectionObserver(update, options);
observer.observe(progress);
function update() {
var element = document.getElementById("progressbar");
var width = 5;
var identity = setInterval(scene, 30);
function scene() {
if (width >= 40) {
clearInterval(identity);
} else {
width++;
element.style.width = width + '%';
element.innerHTML = width * 1 + '%';
}
}
}
</script>
this is the script that I'd like to function on (on my div #progressbar2)
<script>
// start js deel 2
const progress = document.getElementById('progressbar2')
//try this for multiple progressbars
const options = {
threshold : 1
};
let observer = new IntersectionObserver(update, options);
observer.observe(progress);
function update() {
var element = document.getElementById("progressbar2");
var width = 5;
var identity = setInterval(scene, 30);
function scene() {
if (width >= 40) {
clearInterval(identity);
} else {
width++;
element.style.width = width + '%';
element.innerHTML = width * 1 + '%';
}
}
}
</script>
once again I do not know why this doesn't work, I am new to JavaScript. I tried a lot of different things like getdocumentbyclassname but I couldn't get it to work..
please tell my if this is possible in one script or how I could make it work with more scripts.