bobyu
bobyu

Reputation:

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?

Upvotes: 6

Views: 18438

Answers (5)

Rene Saarsoo
Rene Saarsoo

Reputation: 13917

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("container").scrollTop = document.getElementById("item-3").offsetTop;

Upvotes: 9

Steve Harrison
Steve Harrison

Reputation: 125470

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

Upvotes: 2

Fermin
Fermin

Reputation: 36081

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.

Upvotes: 2

Jose Basilio
Jose Basilio

Reputation: 51468

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

Upvotes: 5

Canavar
Canavar

Reputation: 48088

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();">  

Upvotes: 3

Related Questions