Reputation: 49817
I'm trying making inline divs scroll horizontally by clicking on a toggle button, smoothly, but I don't know how to make this work : jsfiddle
Here is my code:
<button class="go">go</button>
<div class="right">right scroll</div>
<div class="left">left scroll</div>
jquery
$(function () {
$('.go').on('click', function(){
$('.left').animate({'left': '-105%'});
$('.right').animate({'left': '0px'});
$(this).toggleClass('return go');
$('.return').bind('click', function(){
$('.left').animate({'left': '0px'});
$('.right').animate({'left': '105%'});
$(this).toggleClass('return go');
});
});
});
css
.left {
min-width:100%;
min-height:300px;
background:red;
position:relative;
float:left;
clear:right;
left:0;
}
.right {
min-width:100%;
min-height:300px;
background:blue;
position:relative;
right:-105%;
float:left;
clear:right;
}
Upvotes: 0
Views: 9884
Reputation: 71918
Not sure if this is what you want:
$(function () {
$('a').on('click', function () {
$('.left').animate({'left': '-105%'});
$('.right').animate({'left': '0px'});
});
});
You were not animating the elements, just setting their CSS. Also, you were setting another click handler on the link on every click (I didn't understand why, so I removed it).
Regarding your updates/comments
To make the divs side-by-side, wrap them in an container with position: relative
, and use position: absolute
on the divs, with top: 0
. Don't use floats.
Don't set a new click handler from within the click handler. That doesn't replace the existing click handler, but adds a new one. So every click does more animations than the previous one (and the visible effect in this case is a delay before the animation starts). Use an if
statement inside you existing click handler instead:
$('a').on('click', function(){
if($('.left').css('left') == '0px') {
$('.left').animate({'left': '-105%'});
$('.right').animate({'left': '0px'});
} else {
$('.left').animate({'left': '0px'});
$('.right').animate({'left': '105%'});
};
});
Upvotes: 1