I have a div with a fixed height of 400 pixels and a long list of elements inside. By clicking on the previous / next links, you will be redirected to the list. The problem is that after a while the current item will be missing. How to move scroll bar with current item?
I made a demo, see: http://jsbin.com/idunaf
<!DOCTYPE html> <html> <head> <style> #listContainer{height:400px;width:300px;overflow:auto;background-color:#eee;} .selectedItem{background-color:white;color:red;} </style> <script class="jsbin" src="http://code.jquery.com/jquery-1.7.1.min.js"></script> <script> for(var a=[],i=0;i<100;++i){ a[i]=i; } currentItem = 0; $(document).ready(function() { var items = []; $.each(a, function(i,x){ items.push('<li id="item_'+x+'">item #'+x+'</li>'); }); $('#list').append(items.join('')); $('#next').click(function() { updateList(); currentItem += 1; }); $('#prev').click(function() { updateList(); currentItem -= 1; }); }); function updateList(){ $('#listContainer').find('.selectedItem').removeClass('selectedItem'); $('#item_'+currentItem).addClass('selectedItem'); } </script> </head> <body> <a href="javascript:void(0)" id="prev"><< PREV ITEM</a> | <a href="javascript:void(0)" id="next">NEXT ITEM >></a> <div id="listContainer"> <ul id="list"></ul> </div> </body> </html>
source share