-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
75 lines (64 loc) · 2.44 KB
/
Copy pathscript.js
File metadata and controls
75 lines (64 loc) · 2.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// Collect DOM elements
const galleryItems = document.querySelectorAll('.gallery-item');
const lightbox = document.getElementById('lightbox');
const lightboxImg = document.getElementById('lightboxImg');
const closeBtn = document.getElementById('closeBtn');
const prevBtn = document.getElementById('prevBtn');
const nextBtn = document.querySelector('.next-btn'); // Targets custom next arrow
// Create an array containing all image sources dynamically
const imgArray = [];
galleryItems.forEach((img) => {
imgArray.push(img.src);
});
// Track the index tracking variable of the active opened image
let currentIndex = 0;
// Function to update the source image inside the lightbox view
function updateLightboxImage() {
lightboxImg.src = imgArray[currentIndex];
}
// 1. Open Lightbox on click
galleryItems.forEach((item) => {
item.addEventListener('click', (e) => {
// Find which specific index number was clicked
currentIndex = parseInt(e.target.getAttribute('data-index'));
// Render image and switch overlay to visible layout style
updateLightboxImage();
lightbox.style.display = 'flex';
});
});
// 2. Close Lightbox event handler
closeBtn.addEventListener('click', () => {
lightbox.style.display = 'none';
});
// Also close lightbox if the user clicks anywhere outside the main image panel
lightbox.addEventListener('click', (e) => {
if (e.target === lightbox) {
lightbox.style.display = 'none';
}
});
// 3. Navigation Controls Logic
function showNextImage() {
currentIndex++;
if (currentIndex >= imgArray.length) {
currentIndex = 0; // Wrap back directly to start index loop
}
updateLightboxImage();
}
function showPrevImage() {
currentIndex--;
if (currentIndex < 0) {
currentIndex = imgArray.length - 1; // Wrap back directly to last image item
}
updateLightboxImage();
}
// Bind navigation layout control buttons to execution triggers
nextBtn.addEventListener('click', showNextImage);
prevBtn.addEventListener('click', showPrevImage);
// 4. Keyboard Arrow Keys Shortcut Support (Extra professional touch!)
document.addEventListener('keydown', (e) => {
if (lightbox.style.display === 'flex') {
if (e.key === 'ArrowRight') showNextImage();
if (e.key === 'ArrowLeft') showPrevImage();
if (e.key === 'Escape') lightbox.style.display = 'none';
}
});