Slider
Sat Oct 01 2022 13:50:32 GMT+0000 (Coordinated Universal Time)
Saved by
@Kristi
#javascript
//HTML
<div class="slider">
<div class="slide"><img src="img/img-1.jpg" alt="Photo 1" /></div>
<div class="slide"><img src="img/img-2.jpg" alt="Photo 2" /></div>
<div class="slide"><img src="img/img-3.jpg" alt="Photo 3" /></div>
<div class="slide"><img src="img/img-4.jpg" alt="Photo 4" /></div>
</div>
//CSS
/* SLIDER */
.slider {
max-width: 100rem;
height: 50rem;
margin: 0 auto;
position: relative;
/* To hide unwanted .slide */
overflow: hidden;
}
.slide {
position: absolute;
top: 0;
width: 100%;
height: 50rem;
display: flex;
align-items: center;
justify-content: center;
/* THIS creates the animation! */
transition: transform 1s;
}
//JS
//Slider
const slides = document.querySelectorAll('.slide');
const btnLeft = document.querySelector('.slider__btn--left');
const btnRight = document.querySelector('.slider__btn--right');
// Set a current slide to begin with
let currentSlide = 0;
//Set a maximum number of slides else number will be infite
const maxSlide = slides.length;
const goToSlide = slide => {
//Change position for each slide
slides.forEach((s, i) => {
//e. currentSlide 1: 100 * (0 - 1) = -100% each item slides left
s.style.transform = `translateX(${100 * (i - slide)}%)`;
});
};
//Show slide on position 0
goToSlide(0);
//Next slide
const nextSlide = () => {
//Reset the value once we reach max
currentSlide === maxSlide - 1
? (currentSlide = 0)
: //Increase by one everytime we click 'next'
currentSlide++;
goToSlide(currentSlide);
};
const prevSlide = () => {
//If it is in position 0 then by pressing prev go to the last slide
currentSlide === 0 ? (currentSlide = maxSlide - 1) : currentSlide--;
goToSlide(currentSlide);
};
btnRight.addEventListener('click', nextSlide);
btnLeft.addEventListener('click', prevSlide);
//Handle keyboar event left-right
document.addEventListener('keydown', function (e) {
if (e.key === 'ArrowRight') nextSlide();
//Also with short-circuting
e.key === 'ArrowLeft' && nextSlide();
});
content_copyCOPY
Navigate slider with arrows
https://www.udemy.com/course/the-complete-javascript-course/learn/lecture/22649001#questions
Comments