Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery scrollLeft is not scrolling

Tags:

html

jquery

css

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">&larr;</button>
<button id="right">&rarr;</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);
  });
});
like image 950
gtr123 Avatar asked Jan 12 '13 03:01

gtr123


1 Answers

you need to scrollLeft the element that has the overflow property, and that's your #outside

jsBin demo

$(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 "-="

like image 60
Roko C. Buljan Avatar answered Sep 23 '22 16:09

Roko C. Buljan