<section>
<div class="block 1">
<div class="slider-box">
<div class="slider">
<div class="slide">
<a href="to some" >
<img src="https://psv4.userapi.com/c848232/u773690/docs/d14/64da44d82e75/1.png">
</a>
</div>
<div class="slide">
<a href="to other">
<img src="https://psv4.userapi.com/c848232/u773690/docs/d14/2cc4ffc3e478/2.png">
</a>
</div>
</div>
</div>
</div>
<hr>
</section>
* {
margin: 0;
padding: 0;
}
section {
width: 100%;
height: 100vh;
background: #ececec;
}
.block {
width: 200px;
height: 100px;
margin: 10px auto;
}
.slider-box {
display: flex;
overflow: hidden;
border: 1px solid #909090;
}
.slider {
display: flex;
transition: 0.5s;
}
.slide {
display: flex;
width: 200px;
height: 100px;
align-items: center;
justify-content: center;
}
.slide a {
pointer-events: none;
}
img {
display: block;
}
class MySlider {
constructor(element) {
this.domCache = {
element,
wrapper: element.querySelector('.slider'),
slides: element.querySelectorAll('.slider .slide')
};
this.state = {
activeSlideIndex: 0
};
this.initControls();
}
initControls() {
const manager = new Hammer.Manager(this.domCache.wrapper);
manager.add(new Hammer.Pan({ threshold: 0, pointers: 0, touchAction: 'auto', recognizers: [[Hammer.Pan,{ direction: Hammer.DIRECTION_HORIZONTAL }],] }));
manager.on('pan', this.onPan.bind(this));
this.domCache.slides.forEach(function(element) {
element.addEventListener("click", function(evt) {
const link = evt.target.querySelector("a");
console.log("window.location = ", link.getAttribute("href"));
});
});
}
onPan(e) {
const sensitivity = 3; // horizontal % needed to trigger swipe
const numberOfSlides = this.domCache.slides.length;
const activeIndex = this.state.activeSlideIndex;
const percentage = 100 / numberOfSlides * e.deltaX / window.innerWidth;
const transformPercentage = percentage - 100 / numberOfSlides * activeIndex;
this.domCache.wrapper.style.transform = `translateX(${transformPercentage}%)`;
if (e.isFinal) {
if( e.velocityX > 1 ) {
this.goToSlide( activeIndex - 1 );
} else if( e.velocityX < -1 ) {
this.goToSlide( activeIndex + 1 )
} else {
if( percentage <= -( sensitivity / numberOfSlides ) )
this.goToSlide( activeIndex + 1 );
else if( percentage >= ( sensitivity / numberOfSlides ) )
this.goToSlide( activeIndex - 1 );
else
this.goToSlide( activeIndex );
}
}
}
goToSlide(index) {
const numberOfSlides = this.domCache.slides.length;
if (index < 0) {
this.state.activeSlideIndex = 0;
} else if (index > numberOfSlides - 1) {
this.state.activeSlideIndex = numberOfSlides - 1
} else {
this.state.activeSlideIndex = index;
}
const percentage = -(100 / numberOfSlides) * this.state.activeSlideIndex;
this.domCache.wrapper.style.transform = `translateX(${percentage}%)`;
}
}
[].forEach.call(document.querySelectorAll('.slider-box'), (element) => {
const slider = new MySlider(element);
});
This Pen doesn't use any external CSS resources.