sunlight76
sunlight76

Reputation: 103

Javascript appendChild (div) : confusion

I'm trying to show the same loader used on "page loading" after a "submit" button is pressed.

At the very top of the page I have:

<div id="gabbia"><div id="load_screen"><div id="loader"></div></div></div>

("gabbia" is just a container while "load_screen" and "loader" are formatted with css to obtain a nice "spinning wheel")

I have this script:

var gabbia = document.getElementById("gabbia");
var load_screen = document.getElementById("load_screen");
var loader = document.getElementById("loader");

window.addEventListener("load", function () {
        gabbia.removeChild(gabbia.childNodes[0]);
    });

function show_loader() {
            var cont = document.getElementById("gabbia");
             cont.appendChild(load_screen);
             var subcont = document.getElementById("load_screen");
             subcont.appendChild(loader);
        }

It seems that on show_loader() call, the first DIV (load_screen) is added, while the second (loader) is not added as child to rebuild the loader.

I never used javascript before, sorry. Thanks for your help to understand.

Upvotes: 0

Views: 85

Answers (1)

Jonas Wilms
Jonas Wilms

Reputation: 138267

I dont know were the error is. I believe its because you used document.getElementById at the wrong position (before page load). I would do ( a more easy + efficient way using css):

window.addEventListener("load",loader);

function loader(val) {
     document.getElementById("gabbia").style.display=val?"block":"none";
}

Use like this:

loader();//hide
loader(false)//hide
loader(true)//show

Upvotes: 1

Related Questions