Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
65 lines (54 loc) · 2.55 KB
/
Copy pathscript.js
File metadata and controls
65 lines (54 loc) · 2.55 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
const slidesEl = document.getElementById('slides');
const indicatorsEl = document.getElementById('indicators');
const captionEl = document.getElementById('caption');
const prevBtn = document.getElementById('prevBtn');
const nextBtn = document.getElementById('nextBtn');
const images = [
{ url: 'https://images.pexels.com/photos/417074/pexels-photo-417074.jpeg?auto=compress&cs=tinysrgb&w=800', caption: 'Mountain Landscape' },
{ url: 'https://images.pexels.com/photos/1108099/pexels-photo-1108099.jpeg?auto=compress&cs=tinysrgb&w=800', caption: 'Ocean Sunset' },
{ url: 'https://images.pexels.com/photos/1287145/pexels-photo-1287145.jpeg?auto=compress&cs=tinysrgb&w=800', caption: 'Forest Trail' },
{ url: 'https://images.pexels.com/photos/1287142/pexels-photo-1287142.jpeg?auto=compress&cs=tinysrgb&w=800', caption: 'Desert Dunes' },
{ url: 'https://images.pexels.com/photos/1366919/pexels-photo-1366919.jpeg?auto=compress&cs=tinysrgb&w=800', caption: 'City Skyline' },
];
let current = 0;
let autoPlayInterval = null;
function buildCarousel() {
images.forEach((img, i) => {
const slide = document.createElement('div');
slide.className = 'slide';
slide.style.backgroundImage = `url(${img.url})`;
slidesEl.appendChild(slide);
const dot = document.createElement('div');
dot.className = 'indicator';
dot.addEventListener('click', () => goTo(i));
indicatorsEl.appendChild(dot);
});
update();
}
function update() {
slidesEl.style.transform = `translateX(-${current * 100}%)`;
document.querySelectorAll('.indicator').forEach((dot, i) => {
dot.classList.toggle('active', i === current);
});
captionEl.textContent = images[current].caption;
}
function goTo(index) { current = (index + images.length) % images.length; update(); resetAutoPlay(); }
function next() { goTo(current + 1); }
function prev() { goTo(current - 1); }
function startAutoPlay() { autoPlayInterval = setInterval(next, 4000); }
function resetAutoPlay() { clearInterval(autoPlayInterval); startAutoPlay(); }
nextBtn.addEventListener('click', next);
prevBtn.addEventListener('click', prev);
document.addEventListener('keydown', (e) => {
if (e.key === 'ArrowRight') next();
if (e.key === 'ArrowLeft') prev();
});
const carousel = document.getElementById('carousel');
let touchStartX = 0;
carousel.addEventListener('touchstart', (e) => { touchStartX = e.touches[0].clientX; });
carousel.addEventListener('touchend', (e) => {
const diff = touchStartX - e.changedTouches[0].clientX;
if (Math.abs(diff) > 50) { diff > 0 ? next() : prev(); }
});
buildCarousel();
startAutoPlay();