How to save current item in div overflow mode?

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> 
+4
source share
1 answer

You should be able to use the DOM (non-jQuery) element.scrollIntoView() method:

 $('#item_'+currentItem).addClass('selectedItem')[0].scrollIntoView(true); // or $('#item_'+currentItem)[0].scrollIntoView(true); // or document.getElementById('item_'+currentItem).scrollIntoView(true); 

[0] - it's just getting a reference to the actual DOM element from a jQuery object - if you select by id, I assume that only one element can match the selector. Of course, with most jQuery methods to resolve the chain, you can do this at the end of the existing .addClass() , rather than selecting the item again.

(See .scrollIntoView() doco to decide whether to pass this method true or false (or nothing).)

+2
source

Source: https://habr.com/ru/post/1384636/


All Articles