Skip to content

Instantly share code, notes, and snippets.

@edwardlorilla
Created May 7, 2021 15:46
Show Gist options
  • Save edwardlorilla/127b4869d912facea4e4162ecf1ddd63 to your computer and use it in GitHub Desktop.
Save edwardlorilla/127b4869d912facea4e4162ecf1ddd63 to your computer and use it in GitHub Desktop.
【JAVASCRIPT】seamless carousel
<div id="div">
<div class="rollbox"></div>
</div>
</body>
$(document).ready(function() {
for (var i = 0; i < 7; i++) {
var $item = $("<div class='item'>" + i+ "</div>");
$item.appendTo($("#div .rollbox"));
}
})
//Carousel action
$(function() {
$("#div").roll(1);
})
$.prototype.roll = function(span) {
span = span == undefined ? 20 : span;
var $that = $(this).find('.rollbox');
var index = 0;
var t = setInterval(function() {
$that.css('margin-top', index + 'px');
index--;
check();
}, span)
//
$that.mouseenter(function() {
clearInterval(t);
})
$that.mouseleave(function() {
t = setInterval(function() {
$that.css('margin-top', index + 'px');
index--;
check();
}, span)
})
function check(){
var first = $that.children().first();
var top = parseInt(first.css('margin-top').replace('px',''));
var bottom = parseInt(first.css('margin-bottom').replace('px',''));
var height =first.height();
bw = parseInt(first.css('border-width').replace('px',''));
var temp = index+top+height+bottom;
if(temp==top-2*bw){
var last = $that.children().last();
last.after(first);
$that.css('margin-top','0px');
index=0;
}
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
* {
margin: 0;
padding: 0;
user-select: none;
}
#div {
border: 1px solid lightgray;
width: 600px;
height: 300px;
margin: 20px;
overflow: hidden;
}
.item {
border: 1px solid lightgray;
width: 96%;
height: 50px;
margin: 10px auto;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment