Scrolling DIV

I have a div in which there are a large number of elements. I select these elements dynamically by pressing a button, overflow automatically in my case. I want that when an item that is not displayed is selected to scroll the div so that it can be visible. How can i do this?

+6
javascript dom html
source share
5 answers

You can use the scrollTop property of the HTMLElement property to set the amount by which its contents scroll.

And you can get the amount needed to scroll from the offsetTop of the element you want to scroll.

For example, using 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 can use this JavaScript to scroll the container div in the third paragraph:

 document.getElementById("container").scrollTop = document.getElementById("item-3").offsetTop; 
+9
source share

Another option is to use jQuery with the ScrollTo plugin.

+5
source share

When your button is clicked and the selected item will call this selected focus () method of the selected item. this will automatically scroll the 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();"> 
+3
source share

You can also use the DIV property scrollTop or scrollLeft (depending on whether the scroll is horizontal or vertical).

I did this before and used the setTimeout event so that it scrolls, not in 1 motion. This is without jQuery tho.

+2
source share

Another option ... anchors.

Assign a unique identifier to each element, and when you want to go to a specific element, execute the following JavaScript code:

 location.hash = itemID; 

... where itemID is a variable containing the identifier of the item you want to scroll through.

Steve

+2
source share

All Articles