Если кому интересно, то подсократил код:
(function() {
var HIDDEN_CLASS = "hidden";
var OVERFLOW_BLOCK = "overflow-block";
var MODAL = document.body.querySelector(".modal");
var MODAL_IMAGE = MODAL.querySelector("img");
var MODAL_CAPTION = MODAL.querySelector("p");
var MODAL_BUTTON_CLOSE = MODAL.querySelector(".modal-close");
var MODAL_BUTTON_BACK = MODAL.querySelector(".modal-previous");
var GALLERY_ARRAY = document.body.querySelectorAll(".photos img");
var CURRENT_IMG_ID;
var actionImgModal = {
openImg(modalWindow, modalImg, modalCaption, imagesArray) {
for (var i = 0; i < imagesArray.length; i++) {
imagesArray[i].id = i;
imagesArray[i].onclick = function () {
CURRENT_IMG_ID = this.id;
modalImg.src = this.src;
modalCaption.innerHTML = this.alt;
modalWindow.classList.remove(HIDDEN_CLASS);
document.body.classList.add(OVERFLOW_BLOCK);
};
}
},
closeImg(modalWindow) {
document.body.classList.remove(OVERFLOW_BLOCK);
modalWindow.classList.add(HIDDEN_CLASS);
},
changeImg(modalImg, modalCaption, imagesArray) {
if (CURRENT_IMG_ID == imagesArray.length) { CURRENT_IMG_ID = 0;
} else if (CURRENT_IMG_ID == -1) { CURRENT_IMG_ID = imagesArray.length - 1
}
modalImg.src = imagesArray[CURRENT_IMG_ID].src;
modalImg.alt = imagesArray[CURRENT_IMG_ID].alt;
modalCaption.innerHTML = modalImg.alt;
},
nextImg(modalImg, modalCaption, imagesArray) {
CURRENT_IMG_ID++;
this.changeImg(modalImg, modalCaption, imagesArray);
},
previousImg(modalImg, modalCaption, imagesArray) {
CURRENT_IMG_ID--;
this.changeImg(modalImg, modalCaption, imagesArray);
}
};
actionImgModal.openImg(MODAL, MODAL_IMAGE, MODAL_CAPTION, GALLERY_ARRAY);
MODAL_BUTTON_CLOSE.onclick = function () {
actionImgModal.closeImg(MODAL);
};
MODAL_IMAGE.onclick = function () {
actionImgModal.nextImg(MODAL_IMAGE, MODAL_CAPTION, GALLERY_ARRAY);
};
MODAL_BUTTON_BACK.onclick = function () {
actionImgModal.previousImg(MODAL_IMAGE, MODAL_CAPTION, GALLERY_ARRAY);
};
document.onkeydown = function (evt) {
if (evt.key == "Escape") {
actionImgModal.closeImg(MODAL);
} else if (evt.key == "ArrowRight") {
actionImgModal.nextImg(MODAL_IMAGE, MODAL_CAPTION, GALLERY_ARRAY);
} else if (evt.key == "ArrowLeft") {
actionImgModal.previousImg(MODAL_IMAGE, MODAL_CAPTION, GALLERY_ARRAY);
}
};
})();