This is a script I wrote for a gallery website I’m building for a friend, the intent is to be able to click on any small image in the gallery and have it show up larger, then a second click anywhere in the window should remove the overlayed image and show the gallery again. It IS doing this, but only for the first several clicks, after 7 or 8 open and closings it develops a severe lag and becomes essentially unresponsive (over a minute before it responds to a click). Anything I try to rewrite it either makes it worse or breaks it completely, can anyone see what’s causing this?
// track if the overlay is active
var active = false;
function bigPicture(){
// listen for click and capture the image that is clicked on
window.addEventListener('click', function open(e){
var source = e.target;
// ignore clicks that are on elements other than images
if (!source.hasAttribute('src')){return};
// make a copy of image element
var copy = source.cloneNode();
// select full page div to darken background
var bg = document.getElementById('fullBackground')
// select the container for full-size image
var container = document.getElementById('fullContainer')
// select rest of page behind overlay
var page = document.querySelector('body');
// insert the clicked image into the overlay container and set overlay classes
container.insertAdjacentElement('afterbegin', copy);
bg.className = "overlay";
container.className = "overlay-image"
// prevent scrolling while overlay is active
page.style.overflow = "hidden";
// track that overlay is displaying
active = true;
// add click listener to close overlay
if (active) {
// next click closes overlay and returns to gallery
window.addEventListener('click', function close(e){
bg.className = "";
container.className = "";
container.innerHTML = "";
page.style.overflow = "scroll";
active = false;
bigPicture();
});
}
});
}