JQuery horizontal scrolling (click and animation)

I have a series of divs floating infinitely in a horizontal line. I have a container with a fixed width div, overflow: hidden. Ultimately, I would like to press divs / buttons on the left and right to scroll the elements (against the scrollbar).

I'm having trouble getting .animate () to work. I want each click to move items in the list.

It should work in the same way as the list of Amazons "Customers who bought this product also purchased", which can be scrolled in the same way. I was tempted to try using .mousedown and make it move while holding (it seems like a true scroll), but first want to make this easier approach.

Here is the fiddle and code:

http://jsfiddle.net/stfzy/16/

HTML:

<div id="container"> <div id="arrowL"> </div> <div id="arrowR"> </div> <div id="list-container"> <div class='list'> <div class='item'> </div> <div class='item'> </div> <div class='item'> </div> <div class="item"> </div> </div> </div> 

CSS

  #container{ width:340px; height:50px; } #list-container { overflow:hidden; width: 300px; float:left; } .list{ background:grey; min-width:700px; float:left; } #arrowR{ background:yellow; width:20px; height:50px; float:right; cursor:pointer; } #arrowL{ background:yellow; width:20px; height:50px; float:left; cursor:pointer; } .item{ background:green; width:140px; height:40px; margin:5px; float:left; } 

JQuery

 $(document).ready(function() { $('div#arrowR').click(function(){ $('div.item').animate({'left':'-=300px'}); }); $('div#arrowR').click(function(){ $('div.item').animate({'left':'+=300px'}); }); }); 

Any help is appreciated. Thanks!

+6
source share
1 answer

Add position:relative to .item , for example:

 .item{ background:green; width:140px; height:40px; margin:5px; float:left; position:relative; /* Put me here! */ } 

Working example: http://jsfiddle.net/mattblancarte/stfzy/21/

There are a few more errors in your setup, but this should make you unstick. :)

Edit ::

Here is a short solution to solve the problem when the list will slide too far in any direction:

 $(document).ready(function() { var $item = $('div.item'), //Cache your DOM selector visible = 2, //Set the number of items that will be visible index = 0, //Starting index endIndex = ( $item.length / visible ) - 1; //End index (NOTE:: Requires visible to be a factor of $item.length... You can improve this by rounding...) $('div#arrowR').click(function(){ if(index < endIndex ){ index++; $item.animate({'left':'-=300px'}); } }); $('div#arrowL').click(function(){ if(index > 0){ index--; $item.animate({'left':'+=300px'}); } }); }); 
+17
source

All Articles