Pedro Estevao Pedro Estevao - 4 years ago 114
Javascript Question

Change "right" / "left" slowly

I have 5 images wrapped in a absolutely positioned div. When I click "next" button I set div's

right: 0
and when I click "previous" button I set div's
left: 0
.

So it behaves like a horizontal slider of images.

What I need now is to add animation to this transition. I want this div to "move" slowly.

I tried this:

$('.slider').animate({right:'0'}, 1000);


Instead of
$('.slider').css('right','0');


But it didn't work. The div moves to the right with no animation.

Here is the code with snippet:



$('.arrow-right').on('click', function() {
$('.slider').attr('style', '');
$('.slider').css('right','0');
$('.arrow').toggle();
});

$('.arrow-left').on('click', function() {
$('.slider').attr('style', '');
$('.slider').css('left','0');
$('.arrow').toggle();
});

.container {
height: 130px;
margin-bottom: 20px;
overflow: hidden;
position: relative;
white-space: nowrap;
background: grey;
width: 420px;
}

.arrow {
text-align: center;
margin-top: 4px;
font-size: 26px;
cursor: pointer;
display: block;
}

.arrow-left {
background: rgba(255,255,255,0.8);
padding: 10px;
padding-left: 2px;
border-top-right-radius: 30px;
border-bottom-right-radius: 30px;
position: absolute;
left: 0;
top: 47px;
color: #4c4c4c;
cursor: pointer;
z-index: 999;
}

.arrow-right {
background: rgba(255,255,255,0.8);
padding: 10px;
padding-right: 2px;
border-top-left-radius: 30px;
border-bottom-left-radius: 30px;
position: absolute;
right: 0;
top: 47px;
color: #4c4c4c;
cursor: pointer;
z-index: 999;
}

.slider {
position: absolute;
}

.slider img {
height: 130px;
width: 130px;
}

.hide {
display: none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<span class="arrow hide">
<i class="fa fa-chevron-left arrow-left"></i>
</span>
<div class="slider">
<img src="1.jpg">
<img src="2.jpg">
<img src="3.jpg">
<img src="4.jpg">
<img src="5.jpg">
</div>
<span class="arrow">
<i class="fa fa-chevron-right arrow-right"></i>
</span>
</div>




Answer Source

You cannot animate an absolute dive from left:0 to right:0.

You need to calculate left position and animate from 0 to new left.
Also $('.slider').attr('style', ''); will remove position:absolute, so just comment it.

$('.arrow-right').on('click', function() {  
    //$('.slider').attr('style', '');
    var left = $('.slider').outerWidth() - $('.container').outerWidth();
    $('.slider').animate({left:'-'+left+'px'}, 1000);
    $('.arrow').toggle();
});

$('.arrow-left').on('click', function() {
    //$('.slider').attr('style', '');
    $('.slider').animate({left:'0'}, 1000);
    $('.arrow').toggle();
});    

See this Fiddle

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download