Skip to content

Instantly share code, notes, and snippets.

@pascalmaddin
Created June 17, 2013 09:54
Show Gist options
  • Save pascalmaddin/5795853 to your computer and use it in GitHub Desktop.
Save pascalmaddin/5795853 to your computer and use it in GitHub Desktop.
Really simple jQuery-Slider. Just the basic structure.
<!doctype html>
<html>
<head>
<meta charset=utf-8>
<title>The Obligatory Slider</title>
<style>
body {
width: 600px;
margin: 100px auto 0;
}
* { margin: 0; padding: 0; }
</style>
<link rel="stylesheet" href="slider.css">
</head>
<body>
<div class="slider">
<ul>
<li><img src="img/img1.gif" alt="image"></li>
<li><img src="img/img2.gif" alt="image"></li>
<li><img src="img/img3.gif" alt="image"></li>
<li><img src="img/img4.gif" alt="image"></li>
<li><img src="img/img1.gif" alt="image"></li>
<li><img src="img/img2.gif" alt="image"></li>
<li><img src="img/img3.gif" alt="image"></li>
<li><img src="img/img4.gif" alt="image"></li>
</ul>
</div>
<div id="slider-nav">
<button data-dir="prev">Previous</button>
<button data-dir="next">Next</button>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="slider.js"></script>
</body>
</html>
#slider-nav {
display: none;
margin-top: 1em;
}
#slider-nav button {
padding: 1em;
margin-right: 1em;
border-radius: 10px;
cursor: pointer;
}
.slider {
width: inherit;
height: 300px;
overflow: scroll;
}
.slider ul {
width: 10000px;
list-style: none;
}
.slider li {
float: left;
}
// the procedural method
(function($) {
var sliderUL = $('div.slider').css('overflow', 'hidden').children('ul'),
imgs = sliderUL.find('img'),
imgWidth = imgs[0].width, // 600
imgsLen = imgs.length, // 4
current = 1,
totalImgsWidth = imgsLen * imgWidth; // 2400
$('#slider-nav').show().find('button').on('click', function() {
var direction = $(this).data('dir'),
loc = imgWidth; // 600
// update current value
( direction === 'next' ) ? ++current : --current;
// if first image
if ( current === 0 ) {
current = imgsLen;
loc = totalImgsWidth - imgWidth; // 2400 - 600 = 1800
direction = 'next';
} else if ( current - 1 === imgsLen ) { // Are we at end? Should we reset?
current = 1;
loc = 0;
}
transition(sliderUL, loc, direction);
});
function transition( container, loc, direction ) {
var unit; // -= +=
if ( direction && loc !== 0 ) {
unit = ( direction === 'next' ) ? '-=' : '+=';
}
container.animate({
'margin-left': unit ? (unit + loc) : loc
});
}
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment