gtr123
gtr123

Reputation: 318

jQuery scrollLeft is not scrolling

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

Upvotes: 7

Views: 13773

Answers (3)

Roko C. Buljan
Roko C. Buljan

Reputation: 205979

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

Upvotes: 12

Adam Merrifield
Adam Merrifield

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

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167162

Works perfectly

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

Corrections

  1. And when you give a float: left; you need to clear your floats. Please wait till the fiddle is ready...
  2. You haven't loaded the jQuery in your fiddle.
  3. Need to give position: relative; to the UL.

Fiddle: http://jsfiddle.net/BQPVL/9/

Upvotes: 1

Related Questions