1

Apologies, I don't have formal training in Javascript. I am trying to make a function that operates a loading progress bar. I'd like to add the "donezo" class to #ammount upon completion. However, the class is not being added. I believe the variables are initialized correctly. Doing a querySelector instead of the "ammount" var does seem to work. Hopefully someone can explain why this is the case to me? Much appreciated.

codepen here

(function move() {
    var ammount = document.getElementById("ammount");
    var counter = document.getElementById("counter");
    var wrapper = document.getElementById("wrapper");
    var status = 1;
    var loader = setInterval(fireZeLoader, 10);

    function fireZeLoader() {
        if (status >= 100) {
            clearInterval(loader);
            wrapper.innerHTML = wrapper.innerHTML + '<div class="finished">Complete</div>';
            ammount.classList.add("donezo");
        } else {
            status++;
            ammount.style.width = status + '%';
            counter.innerHTML = status + '%';
        }
    }
}());

1 Answers1

2

It happens because when you modify wrapper.innerHTML the DOM inside wrapper is re-created. That is, all references that you've got beforehand are now pointing to objects which are not on the screen anymore. You can swap these two lines:

ammount.classList.add("donezo");
wrapper.innerHTML = wrapper.innerHTML + '<div class="finished">Complete</div>';

Another option is to carefully modify DOM without assigning to innerHTML, I'd recommend doing the latter.

Community
  • 1
  • 1
yeputons
  • 8,478
  • 34
  • 67
  • Thank you! I just realized I've been spelling "amount" incorrectly too, haha. – user5494847 May 14 '16 at 23:13
  • @user5494847 glad it helped. If you think my answer fully answers your question, please accept it ([more info](http://stackoverflow.com/help/someone-answers)) – yeputons May 15 '16 at 05:07