JVG
JVG

Reputation: 21170

Javascript - Function works once, but never again

I'm building a very simple lightbox script; when you click a button, the lightbox is created. When you click on the lightbox background, it is removed.

The first time you call the function it works just fine. Click button, lightbox shows, click lightbox, it disappears. However, if you try to click the button AGAIN, nothing happens - the div isn't called. No console errors or anything, don't know what the problem is.

JSFIDDLE http://jsfiddle.net/3fgTC/

CODE

function closeLightBox(){
        document.body.removeChild(lightBox);
}

function createElem(){
    var elem = "<div id='lightBox'></div>";
    var bodyElem = document.body;
        bodyElem.innerHTML = elem + bodyElem.innerHTML;
    var lightBox = document.getElementById("lightBox");
        lightBox.style.width = "100%";
        lightBox.style.height = "800px";
        lightBox.style.backgroundColor = "rgba(0,0,0,.5)";
        lightBox.onclick = function(){
            closeLightBox();
        }
}
var button = document.getElementsByClassName("btn");
    for (var i = 0; i<button.length; i++){
        button[i].onclick = function(){
            createElem();
        }
    }

Any ideas?

Upvotes: 1

Views: 209

Answers (1)

icktoofay
icktoofay

Reputation: 129119

Don't prepend to innerHTML; that makes the browser re-parse the HTML and re-create every DOM element, losing event handlers in the process. Instead, use document.createElement:

var lightBox = document.createElement('div');
document.body.insertBefore(lightBox, document.body.firstChild);

Furthermore, inline closeLightBox:

lightBox.onclick = function() {
    document.body.removeChild(lightBox);
}

Try it.

Upvotes: 6

Related Questions