I have a div that has a large number of items in it. I select these items dynamically by clicking a button, overflow is auto in my case. What I want is that when an item that is not visible is selected to scroll the div so that can be visible. How can I do this?
When your button clicked and an item selected call this selected item's focus() method. this will cause auto scroll to your element :
<div style="height:80px; overflow:auto;">
<input type="text" id="id1"><br><br>
<input type="text" id="id2"><br><br>
<input type="text" id="id3"><br><br>
<input type="text" id="id4"><br><br>
<input type="text" id="id5"><br><br>
<input type="text" id="id6"><br><br>
</div>
<input type="button" onclick="document.getElementById('id6').focus();">
You could also use the DIV's scrollTop or scrollLeft property (depending on if the scroll is horizontal or vertical).
I've done this before and used a setTimeout event to make it scroll fluidly, rather than in 1 motion. This is without JQuery tho.
Yet another option... anchors.
Assign each item a unique ID, and when you want to scroll to a particular item, execute the following JavaScript code:
location.hash = itemID;
...where itemID
is a variable that contains the ID of the element you want to scroll to.
Steve
You can use the scrollTop property of HTMLElement to set the amount its content is scrolled by.
And you can get the amount you need to scroll by from offsetTop of the element to which you want to scroll.
For example with this HTML:
<div id="container">
<p id="item-1">foo</p>
<p id="item-2">bar</p>
<p id="item-3">baz</p>
</div>
You could use this JavaScript to scroll the container div to third paragraph:
document.getElementById("contaner").scrollTop = document.getElementById("item-3").offsetTop;