Skip to content

Instantly share code, notes, and snippets.

@Akifcan
Created January 18, 2023 19:13
Show Gist options
  • Save Akifcan/de713a07b02b165d99c8d21229b4047a to your computer and use it in GitHub Desktop.
Save Akifcan/de713a07b02b165d99c8d21229b4047a to your computer and use it in GitHub Desktop.
Swiper clone
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
.slider {
--width: 400px;
--height: 200px;
margin: 1rem;
width: var(--width);
height: var(--height);
outline: 1px solid red;
display: flex;
overflow-x: auto;
}
.slider-item {
background: var(--color);
width: var(--width);
flex-shrink: 0;
color: white;
font-size: 60px;
}
</style>
</head>
<body>
<div class="slider">
<div class="slider-item" style="--color: red">1</div>
<div class="slider-item" style="--color: blue">2</div>
<div class="slider-item" style="--color: pink">3</div>
</div>
<script>
let counter = 0
const slider = document.querySelector('.slider')
const WIDTH = slider.clientWidth
let lastpos = 0
const items = Array.from(slider.querySelectorAll('.slider-item'))
slider.addEventListener('scroll', () => {
if (slider.scrollLeft === 0) {
cloneElements(false)
removeEls()
}
if (slider.scrollLeft === slider.scrollWidth - slider.clientWidth) {
cloneElements(true)
removeEls()
}
})
cloneElements(false)
function removeEls() {
const x = Array.from(slider.querySelectorAll('.slider-item'))
console.log(x.length)
if (x.length > 20) {
for (const i of x) {
i.remove()
}
}
}
function cloneElements(isForward) {
const x = Array.from(slider.querySelectorAll('.slider-item'))
const curr = isForward ? items : items.slice().reverse()
curr.forEach(x => {
const el = x.cloneNode(true)
if (isForward) {
slider.append(el)
slider.scrollTo(slider.scrollLeft, 0)
} else {
slider.prepend(el)
slider.scrollTo(WIDTH * items.length, 0)
}
})
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment