Skip to content

Instantly share code, notes, and snippets.

@wunnle
Last active January 22, 2017 21:26
Show Gist options
  • Save wunnle/a9b78165a98eb27202dc8d1f41a069c1 to your computer and use it in GitHub Desktop.
Save wunnle/a9b78165a98eb27202dc8d1f41a069c1 to your computer and use it in GitHub Desktop.
Scroll-friendly Carousel
<section class="slider">
<ul>
<li>
<img src="https://images.unsplash.com/photo-1464254786740-b97e5420c299?dpr=1&auto=format&fit=crop&w=1500&h=1000&q=80&cs=tinysrgb&crop=" alt="" />
</li><!--
--><li></li><!--
--><li></li><!--
--><li></li><!--
--><li></li></ul>
</section>
$(function(){
$(".slider li").css("background-image", "url(" + $(this).find("img").attr("src") +")")
});
let slideW = 200;
let slideM = 8;
let slideTW = slideW + slideM*2;
let autoscrolled;
$(".slider").scroll(function() {
if(!autoscrolled) {
//console.log($(this).scrollLeft());
let scrollPos = $(this).scrollLeft();
let scrollMod = scrollPos % slideTW;
var scrollTimes = Math.floor((scrollPos - slideTW/2) / slideTW) + 1 ;
console.log(scrollMod, "scrollMod");
console.log(scrollTimes, "scrollTimes");
clearTimeout($.data(this, 'scrollTimer'));
$.data(this, 'scrollTimer', setTimeout(function() {
autoscrolled = true;
$(".slider").animate({ scrollLeft: scrollTimes * slideTW + "px" }, {duration: 300});
setTimeout(function() {
autoscrolled = false;
}, 400)
}, 300));
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
* {
margin: 0;
padding: 0;
}
body {
padding: 30px;
}
$slideW: 200px;
$slideM: 8px;
.slider {
width: 320px;
padding: 0;
height: 300px;
overflow: auto;
white-space: nowrap;
}
.slider ul {
margin: 0 $slideW/4 + $slideM / 4;
display: inline-block;
}
.slider li {
display: inline-block;
position: relative;
height: 200px;
width: 200px;
background-size: cover;
white-space: nowrap;
margin: 0 $slideM;
}
.slider img {
display: none;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment