Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery click event, using next and prev to scroll list items to the top of a div

I am trying to use a click event to scroll the next and previous list items to the top of the div and when it gets to the end it shows the first, making it circular. And if possible also make it auto scroll down every one minute.

I have an expample below that I have adapted from another post:

Instead if showing one at a time I want to show as many that can fit in the div. I know I some how need to change the var currli to check what's currently at the top and change the nextli to scroll the next li to the top.

Any help is greatly appreciated =]

<a id="scrollup" href="#">up</a>  
<a id="scrolldown" href="#">down</a>  
<div id="news">
   <ul>
      <li>item One</li>
      <li>item Two</li>
      <li>item Three</li>
      <li>item Four</li>
      <li>item Five</li>
      <li>item Six</li>
      <li>item Seven</li>
   </ul>
</div>

Here is the jQuery

$(document).ready(function () {


    $('#arrowdown').click(function(event) {
            event.preventDefault();         // cancel click through
            // get current list item
            var currli = $('#news li:visible');
            // get next list item
            var nextli = currli.next();
            // if nextli length is 0, make it equal to first li
            if (nextli.length == 0) {
                nextli = currli.siblings('#news li:first');
            }
            currli.hide();
            nextli.show();
    });
    $('#arrowup').click(function(event) {
            event.preventDefault();         // cancel click through
            // get current list item
            var currli = $('#news li:visible');
            // get next list item
            var prevli = currli.prev();
            // if nextli length is 0, make it equal to first li
            if (prevli.length == 0) {
                prevli = currli.siblings('#news li:last');
            }
            currli.hide();
            prevli.show();
    });
    $('#news li:nth-child(1)').show();

});

Here is the jsFiddle link: http://jsfiddle.net/bambam007/kyf9e/

like image 271
Chemi Avatar asked Nov 03 '22 19:11

Chemi


1 Answers

You can do simply like this:

     $('#scrollup, #scrolldown').click(function(e) {
            e.preventDefault();   
            var id = e.target.id;
        if(id == 'scrollup'){
            $('li:first').appendTo('ul');
        }else{
            $('li:last').prependTo('ul');
        }
    });
like image 90
Alex Ball Avatar answered Nov 15 '22 07:11

Alex Ball