Created
May 17, 2018 14:35
-
-
Save ancyrweb/0620fcf10e0f1d1a5432032fbf9bce16 to your computer and use it in GitHub Desktop.
Home-made simple carousel
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<title>Carousel</title> | |
<style type="text/css"> | |
.container { | |
height: 300px; | |
width: 500px; | |
border: 2px solid black; | |
position: relative; | |
overflow: hidden; | |
} | |
.container-content { | |
position: absolute; | |
left: 0; | |
top: 0; | |
} | |
.item { | |
display: inline-block; | |
margin: 0; | |
padding: 0; | |
} | |
.item1 { background-color: yellow } | |
.item2 { background-color: green } | |
.item3 { background-color: deepskyblue } | |
</style> | |
</head> | |
<body> | |
<div class="container"> | |
<div class="container-content"> | |
<div class="item item1"></div><!-- | |
--><div class="item item2"></div><!-- | |
--><div class="item item3"></div> | |
</div> | |
</div> | |
<script | |
src="https://code.jquery.com/jquery-3.3.1.min.js" | |
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" | |
crossorigin="anonymous"></script> | |
<script type="text/javascript"> | |
$.fn.carousel = function() { | |
var $this = $(this); | |
var $contentContainer = $this.children(); | |
var $children = $contentContainer.children(); | |
var height = $this.height(); | |
var width = $this.width(); | |
var index = 0; | |
var elements = $children.length; | |
// We have to take into account the content container original width | |
var totalWidth = $contentContainer.outerWidth(); | |
$children.each(function() { | |
// We compute every item's height/width so it fits into the container | |
// We deduce the original outerHeight/width because the borders must also fit in | |
$(this).css("height", height - $(this).outerHeight()); | |
$(this).css("width", width - $(this).outerWidth()); | |
totalWidth += $(this).outerWidth(); | |
}); | |
$contentContainer.css("width", totalWidth); | |
var api = { | |
next: function() { | |
carousel = (carousel + 1) % elements; | |
$contentContainer.animate({ | |
left: (-100 * carousel) + "%", | |
}, 500); | |
} | |
} | |
return api; | |
}; | |
var $container = $('.container').first(); | |
var api = $container.carousel(); | |
setInterval(function() { | |
api.next(); | |
}, 2000) | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment