
An awesome image slider that slides smoothly between pictures when you scroll up or down the page.
It also applies a subtle parallax effect to images when they’re scrolled.
How to use it:
1. The HTML structure for the parallax slider.
<main>
<div class="slider">
<div class="slider-inner">
<div class="item">
<div class="image"></div>
</div>
<div class="item">
<div class="image"></div>
</div>
<div class="item">
<div class="image"></div>
</div>
<div class="item">
<div class="image"></div>
</div>
<div class="item">
<div class="image"></div>
</div>
<div class="item">
<div class="image"></div>
</div>
</div>
</div>
</main>2. The necessary CSS styles.
main {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100vh;
}
.slider {
position: absolute;
top: 0;
left: 0;
width: 2800px;
height: 100%;
}
.slider-inner {
position: absolute;
top: 15%;
height: 70%;
width: 100%;
display: flex;
justify-content: space-around;
}
.item {
position: relative;
width: 400px;
height: 100%;
overflow: hidden;
}
.image {
position: absolute;
left: -100px;
width: 600px;
height: 100%;
background-size: cover;
background-position: center;
}3. Add background images to the parallax slider. Note that you can also add background images to each slide using CSS background property.
images.forEach((image, index) => {
image.style.backgroundImage = `url(./images/${index+1}.jpg)`
})4. The main JavaScript to activate the parallax slider.
let images = [...document.querySelectorAll('.image')];
let slider = document.querySelector('.slider');
let sliderWidth;
let imageWidth;
let current = 0;
let target = 0;
let ease = 0.05;
window.addEventListener('resize', init)
// Linear interpolation function
function lerp(start, end, t) {
return start * (1-t) + end * t;
}
// Transform function
function setTransform(el, transform) {
el.style.transform = transform;
}
// Init function
function init() {
sliderWidth = slider.getBoundingClientRect().width;
imageWidth = sliderWidth/images.length;
document.body.style.height = `${sliderWidth - (window.innerWidth - window.innerHeight)}px`
}
// Animating slider
function animate() {
current = parseFloat(lerp(current, target, ease)).toFixed(2);
target = window.scrollY;
setTransform(slider, `translateX(${-current}px)`)
animateImages()
requestAnimationFrame(animate)
}
// Animating images for parallax effect
function animateImages() {
let ratio = current / imageWidth;
let intersectionRatioValue;
images.forEach((image, index) => {
intersectionRatioValue = ratio - (index * 0.7)
setTransform(image, `translateX(${intersectionRatioValue * 70}px)`)
})
}
init()
animate()






