james Oduro james Oduro - 15 days ago 5
jQuery Question

Slide a div sequentially

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;
});

Answer

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>

Comments