Beep Beep - 4 months ago 22
HTML Question

Javascript conflicting with eachover

I have two pieces of java script, one for showing the result percentage in a progress bar, one to show the speed in a different bar.

at the moment only one bar is reviving data the other is not.

Javascrip

// Progress bar javascrip reults
{
var elem = document.getElementById("myBar");
var width = 0;
var id = setInterval(frame, 50);

function frame() {
if (width >= document.getElementById("results-percentile-2").innerHTML) {
clearInterval(id);
} else {
width++;
elem.style.width = width + '%';
document.getElementById("demo").innerHTML = width * 1 + '%';
}
}
}

// End javascript progress bar results

// Progress bar javascrip speed
{
var elem = document.getElementById("myBarspeed");
var width = 0;
var id = setInterval(frame, 50);

function frame() {
if (width >= document.getElementById("results-speed").innerHTML) {
clearInterval(id);
} else {
width++;
elem.style.width = width + '%';
document.getElementById("speed").innerHTML = width * 1 + '%';
}
}
}

// End javascript progress bar speed


HTML

<div class="scale-container-main ">
<div id="percentile-scale" class="scale">

results bar: Your results
<div id="demo">0%</div>
<div class="myProgress">
<div id="myBar" style="width:0"></div>
</div>

speed bar: Your speed
<div id="speed">0%</div>
<div class="myProgress">
<div id="myBarspeed" style="width:0"></div>
</div>

</div>
</div>

Answer

You could use let instead of var inside each block, and

let frame = function() { .... }

but frame would have to be moved above setInterval line

Also, the above only works on recent decent broswers, which means it wont work in IE

An alternative, equally valid method is to use IIFE's - this works in IE!

(function() {
    var elem = document.getElementById("myBar");
    var width = 0;
    var id = setInterval(frame, 50);

    function frame() {
        if (width >= document.getElementById("results-percentile-2").innerHTML) {
            clearInterval(id);
        } else {
            width++;
            elem.style.width = width + '%';
            document.getElementById("demo").innerHTML = width * 1 + '%';
        }
    }
}());

// End javascript progress bar results

// Progress bar javascrip speed
(function() {
    var elem = document.getElementById("myBarspeed");
    var width = 0;
    var id = setInterval(frame, 50);

    function frame() {
        if (width >= document.getElementById("results-speed").innerHTML) {
            clearInterval(id);
        } else {
            width++;
            elem.style.width = width + '%';
            document.getElementById("speed").innerHTML = width * 1 + '%';
        }
    }
}());

The only advantage to the above is that variable names can be useful and meaningful and guaranteed not to clash with anything else (sort of)