a-seat-for-the-sea
clone your own copy | download snapshot

Snapshots | iceberg

Inside this repository

script.js
application/javascript

Download raw (2.2 KB)

// Get the modal
const modal = document.getElementById("modalbox");
const modalImg = document.getElementById("modalImage");
const captionText = document.getElementById("modalCaption");
const closeBtn = document.getElementsByClassName("close")[0];
const leftBtn = document.getElementsByClassName('leftArrow')[0];
const rightBtn = document.getElementsByClassName('rightArrow')[0];

let pageImages = []
let hiResImages = []
let descriptions = []

let imgIndex = 0;

document.querySelectorAll('.gallery--image-img').forEach(i => {
    pageImages.push(i.attributes.src.value);
    hiResImages.push(i.attributes.src.value.split('.')[0].replace("_dither", '.jpg'))
    descriptions.push(i.attributes.alt.value)
});


    
window.onclick = e => {
    if(e.target.tagName == "IMG"){ // Check if we clicked on an image
        let oldIMG = e.target.attributes.src.value; 
        imgIndex = pageImages.findIndex(i => i == oldIMG)
        if (oldIMG.split('.')[0].endsWith('_dither')) {
            newIMG = oldIMG.split('.')[0].replace("_dither", '.jpg')
            // e.target.attributes.src.value = newIMG
        }
        modal.style.display = "flex";
        modalImg.src = newIMG
        captionText.innerHTML = e.target.attributes.alt.value;

    }
} 

// When the user clicks on <span> (x), close the modal
window.onkeydown = (e) => {
    if (e.key == "Escape"){
        closeModal()
    }
    if (e.key == "ArrowLeft"){
        prevImg()
    }
    if (e.key == "ArrowRight"){
        nextImg()
    }
}

const closeModal = () => {
    if (modal.style.display != "none"){
        modal.style.display = "none"
    }
}

const prevImg = () => {
    if (imgIndex != 0){
        imgIndex -= 1;
        modalImg.src = hiResImages[imgIndex]
        captionText.innerHTML = descriptions[imgIndex];

    } else {
        imgIndex = hiResImages.length-1
        modalImg.src = hiResImages[imgIndex]
        captionText.innerHTML = descriptions[imgIndex];

    }
}
const nextImg = () => {
    imgIndex = (imgIndex + 1) % hiResImages.length;
    modalImg.src = hiResImages[imgIndex]
    captionText.innerHTML = descriptions[imgIndex];
}

closeBtn.onclick = closeModal
leftBtn.onclick = prevImg
rightBtn.onclick = nextImg