views:

1460

answers:

5
+3  Q: 

DIV auto scroll

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?

+2  A: 

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();">
Canavar
This doesn't seem to work for regular "div" elements (at least, not in Safari 4 or Firefox 3).
Steve Harrison
I don't try for Safari but Firefox 3 perfectly works.
Canavar
The code you've written there works perfectly. However, if you replace the "input" elements with "div" elements, focusing the div element doesn't seem to scroll to it. See http://cloud.quintusquill.com/dropbox/ScrollTest.html for an example.
Steve Harrison
yes, I understand now, you're right. I thought he was mentioning form elements, In this case I think it's good to use JQuery plugin. thanks !
Canavar
+5  A: 

Yet another option is to use jQuery along with the plugin ScrollTo.

Jose Basilio
+2  A: 

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.

Fermin
+1  A: 

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

Steve Harrison
+5  A: 

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;
Rene Saarsoo