Reputation: 673
I have some items inside slider div and I want to animate left -299px each time click event of skip class is fired and animate back to its noramal position if it reaches its with.
Please how do I achieve this?
I tried but it only animate -299px and it stops.
I have written down some html,css and jquery example:
CSS
<style>
.items{
width:299px;
height:80px;
float:left;
color:white;
}
.slider{
min-width:1495px;
height:80px;
}
.container{
width:299px;
height:80px;
}
.one{
background-color:red;
}
.two{
background-color:yellow;
}
.three{
background-color:red;
}
HTML
<a href='#' class='skip'>Skip</a>
<div class='container'>
<div class='slider'>
<div class='items one'>Item 1</div>
<div class='items two'>Item 2</div>
<div class='items three'>Item 3</div>
</div>
</div>
JQUERY
//skiping check em outerHTML
$(document).on('click','.skip',function(e){
e.preventDefault();
$('.slider').animate({marginLeft:"-299px"},"fast");
//stop default behaviour
return false;
});
Upvotes: 0
Views: 70
Reputation: 21684
Your code is setting the margin-left property to become equal to -299px
. If you wanted this change to work subsequently, you would have to get the previous margin-left
value, and keep decrementing that value by how much you want.
Lucky for you, jQuery saves you the trouble of manually decrementing and supports incremental changes to CSS - just use -=299px
instead of just -299px
.
$(document).on('click','.skip',function(e){
e.preventDefault();
$('.slider').animate({marginLeft:"-=299px"},"fast");
// ^ magic
//stop default behaviour
return false;
});
.items{
width:299px;
height:80px;
float:left;
color:white;
}
.slider{
min-width:1495px;
height:80px;
}
.container{
width:299px;
height:80px;
}
.one{
background-color:red;
}
.two{
background-color:yellow;
}
.three{
background-color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href='#' class='skip'>Skip</a>
<div class='container'>
<div class='slider'>
<div class='items one'>Item 1</div>
<div class='items two'>Item 2</div>
<div class='items three'>Item 3</div>
</div>
</div>
Upvotes: 1
Reputation: 24965
var $slider = $('.slider');
$(document).on('click','.skip',function(e){
e.preventDefault();
if (parseInt($slider.css('marginLeft')) < -(299 * $slider.find('.items').length - 1)) {
$slider.animate({marginLeft:"0px"}, "fast");
} else {
$slider.animate({marginLeft: "-=299px"}, "fast");
}
});
.items{
width:299px;
height:80px;
float:left;
color:white;
}
.slider{
min-width:1495px;
height:80px;
}
.container{
width:299px;
height:80px;
}
.one{
background-color:red;
}
.two{
background-color:yellow;
}
.three{
background-color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href='#' class='skip'>Skip</a>
<div class='container'>
<div class='slider'>
<div class='items one'>Item 1</div>
<div class='items two'>Item 2</div>
<div class='items three'>Item 3</div>
</div>
</div>
Upvotes: 0