Search code examples
javascriptbuttonscrolljquery-selectors

Next/Prev buttons onClick scroll to next and previous <td>'s


I'm still learning JavaScript and need some help. I am making next and previous buttons that cause a scroll to the next or previous <td>'s on the page. I'm trying to implement this to the existing structure of a virb site. the markup looks like this:

div id="next">next</div><div id="prev">prev</div>
<table>
<tr><td>code that includes img</td></tr>
<tr><td>code that includes img</td></tr>
<tr><td>code that includes img</td></tr>
<tr><td>code that includes img</td></tr>
<tr><td>code that includes img</td></tr>
</table>

Here is the script I'm working with:

jQuery.easing.def = "easeInOutQuad";
    $("#next").click(function (){
        //$(this).animate(function(){
            $('html, body').animate({
                scrollLeft: $("td").next.offset().left
                 }, 600);
        //});

    });​

​Here is the jsFiddle I'm working on


Solution

  • The following keeps track of your current item to view. You'll need a similar thig to decrement the index in your 'prev' routine.

    You may also need to add a delay or an event cut-off so that multiple clicks during animation don't take the value of currentIdx above or below the range of items you have to show.

    var currentIdx = 0;
    jQuery.easing.def = "easeInOutQuad";
            $("#next").click(function (){
    
                //$(this).animate(function(){
                    $('html, body').animate({
                        scrollLeft: $("td").eq(currentIdx).offset().left
                         }, 600);
                    currentIdx++;     
                //});
            });