Carousel With CSS & Javascript
Hi ☺. In this article we are going to build Carousel App with CSS and Javascript.
Check The Demo
Start
In mobile devices we can change screen with touch event because we are using -webkit-overflow-scrolling: touch;. For web we will use drag-drop api.
<div class=”slider” ondrop=”drop_handler(event)” ondragover=”dragover_handler(event)”>
<div draggable=”true” class=”slide-item” id=”slide1">
😥
</div>
<div draggable=”true” class=”slide-item” id=”slide2">
🤔
</div>
<div draggable=”true” class=”slide-item” id=”slide3">
🥺
</div>
</div>
Now we added draggable attribute to children elements. Also added the ondrag and ondragover attributes for parent element.
Now we can catch the dragstart event
const slider = document.querySelector(‘.slider’)
slider.addEventListener(‘dragstart’, e => {
console.log(e.target)
}
function dragover_handler(ev) {
ev.preventDefault();
}
function drop_handler(ev) {
ev.preventDefault();
}
After dragstart event start we need to access div’s width. With div’s width we can switch right side or left side.
const sliderWidth = e.target.clientWidth / 2
const clickPosition = e.clientX
As you can we defined the sliderWidth and divided by two. We divided by 2 because we will detect user click side.
Now we will check click side using by clickPosition if clickPosition greater than sliderWidth then we will switch right or else we will switch the left side.
if (clickPosition > sliderWidth) {
console.log(“right”)
}
} else {
console.log(“left”)
}
Now i will define one more variable this variable will determine slide count. Initial value is 1.
let slideIndex = 1
Now i will increase or decrease slideIndex value.
if (clickPosition > sliderWidth) {
slideIndex++
}
} else {
slideIndex —
}
window.location.href = `#slide${slideIndex}`
Now for prevent some errors I need to know length of sliders.
const sliderTotal = document.querySelectorAll(‘.slide-item’).length
Now i will add some controls inside the dragstart event
if (clickPosition > sliderWidth) {
slideIndex++
if (slideIndex > sliderTotal) {
slideIndex = 1
}
} else {
if (slideIndex == 0) {
slideIndex = sliderTotal
} else {
slideIndex —
}
}
If I exceed the slideTotal length slideIndex value will be 1.
If sliderIndex equal to zero then slideIndex value will be sliderTotal length.
Also i don’t want to see drag image so we can remove this drag image
e.dataTransfer.setDragImage(new Image(), 0, 0)
This is the last version of carousel
Thank you for reading. Goodbye👋👋