Reputation: 318
I have a container div
with a ul
inside of it setup like this jsFiddle: http://jsfiddle.net/BQPVL/1/
Why isn't the scroll working?
HTML:
<div id="outside">
<ul id="inside">
<li>hi</li>
<li>how are you?</li>
<li>i am good.</li>
</ul>
</div>
<button id="left">←</button>
<button id="right">→</button>
CSS:
#outside {
width: 200px;
height: 50px;
overflow: scroll;
}
#inside {
width: 1000px;
}
#inside li {
background: red;
width: 99px;
height: 40px;
border-right: 1px solid black;
float: left;
padding: 5px;
}
jQuery:
var position = $("#inside").scrollLeft();
$(document).ready(function() {
$("#right").bind("click", function() {
$("#inside").animate({
scrollLeft: position + 100
}, 1000);
});
});
Upvotes: 7
Views: 13773
Reputation: 205979
you need to scrollLeft
the element that has the overflow
property, and that's your #outside
$(function() { // DOM READY shorthand
$("#right, #left").click(function() {
var dir = this.id=="right" ? '+=' : '-=' ;
$("#outside").stop().animate({scrollLeft: dir+'100'}, 1000);
});
});
as you can see you can attach both your buttons to the click handler, and inside it retrieve the clicked button id
.
If this.id
returns "right"
var dir
wil become "+="
, otherwise logically
you clicked the #left
one and dir
will hold "-="
Upvotes: 12
Reputation: 10407
Try using this: http://jsfiddle.net/BQPVL/10/
$("#right").on("click", function () {
$("#inside").stop(true, true).animate({
left: '-=100'
}, 1000);
});
$("#left").on("click", function () {
$("#inside").stop(true, true).animate({
left:'+=100'
}, 1000);
});
Upvotes: 0
Reputation: 167162
You need to give offset()
or position()
. And animate the left
property.
$(document).ready(function() {
$("#right").bind("click", function() {
var position = $("#inside").position();
$("#inside").animate({
left: position.left - 100
}, 1000);
});
});
$("#left").bind("click", function() {
var position = $("#inside").position();
$("#inside").animate({
left: position.left + 100
}, 1000);
});
float: left;
you need to clear your floats. Please wait till the fiddle is ready...position: relative;
to the UL
.Upvotes: 1