Skip to content

Instantly share code, notes, and snippets.

@khaled0fares
Last active August 13, 2017 06:30
Show Gist options
  • Save khaled0fares/5e3486f102a840d9511218a51040c13b to your computer and use it in GitHub Desktop.
Save khaled0fares/5e3486f102a840d9511218a51040c13b to your computer and use it in GitHub Desktop.
body {
}
.slider{
margin: auto;
width: 400px;
overflow: hidden;
position: relative;
}
.nav {
width: 1200px;
}
li {
width: 400px;
float: left;
list-style-type: none;
}
img {
width: 400px;
}
#next{
position: absolute;
right: -5px;
top: 150px;
}
#prev{
position: absolute;
left: 5px;
top: 150px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="slider.css">
<title></title>
</head>
<body>
<div class="slider">
<ul class="nav">
<li><img src="imgs/one.png" /></li>
<li><img src="imgs/two.png" /></li>
<li><img src="imgs/three.png" /></li>
</ul>
<div class="pointer">
<button id="next" data-dir="next">Next</button>
<button id="prev" data-dir="prev">Previous</button>
</div>
</div>
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
<script src="main.js"></script>
<script src="slider.js"></script>
</body>
</html>
{
$(document).ready(()=>{
const slider = new Slider($('.slider'))
$('button').on('click',function (e){
let direction = $(this).data('dir')
slider.animate(direction)
})
})
let Slider = function(container){
this.nav = container.find('ul')
this.current = 0
let imgs = this.nav.find('img')
this.imgsLength = imgs.length
this.imgWidth = $(imgs[0]).width()
}
Slider.prototype.updateCurrent = function(){
this.current += this.direction === 'next' ? 1 : -1
this.current = (this.current < 0) ? (this.imgsLength -1) : (this.current % this.imgsLength)
}
Slider.prototype.setOperator = function(){
this.operator = "-"
this.operator = (this.current === 0) ? undefined : this.operator
}
Slider.prototype.setMargin = function(){
this.marginLeft = !this.operator ? 0 : `-${this.current * this.imgWidth}`
}
Slider.prototype.animate = function(direction){
this.direction = direction
this.updateCurrent()
this.setOperator()
this.setMargin()
this.nav.stop().animate({'margin-left':this.marginLeft}, 1000)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment