views:

2463

answers:

4

I have a scrolled div and I want to have a link when I click on it it will force this div to scroll to view an element inside. I wrote its javascript like this:

document.getElementById(chr).scrollIntoView(true);

but this scrolls all the page while scrolling the div itsself. How to fix that?

I want to say it like that

MyContainerDiv.getElementById(chr).scrollIntoView(true);
A: 

I'm not sure how attached you are to your current setup. If it were me, I'd turn the div into an iframe, and just do this linked scroll using anchor tags.

Frakkle
+3  A: 

You would have to find the poistion of the element in the DIV you want to scroll to, and set the scrollTop property.

divElem.scrollTop = 0;

Update:

Sample code to move up or down

  function move_up() {
    document.getElementById('divElem').scrollTop += 10;
  }

  function move_down() {
    document.getElementById('divElem').scrollTop -= 10;
  }
Glennular
not working at all like this
Amr ElGarhy
i want to scroll it view, to see it not scrolling with a certain value
Amr ElGarhy
+2  A: 
Cshift3iLike
+2  A: 

You need to get the top offset of the element you'd like to scroll into view, relative to its parent (the scrolling div container):

var topPos = document.getElementById('element_within_div').offsetTop;

The variable topPos is now set to the distance between the top of the scrolling div and the element you wish to have visible (in pixels).

Now we tell the div to scroll to that position using scrollTop():

document.getElementById('scrolling_div').scrollTop = topPos;

If you're using the prototype JS framework, you'd do the same thing like this:

var posArray = $('element_within_div').positionedOffset();
$('scrolling_div').scrollTop = posArray[1];

Again, this will scroll the div so that the element you wish to see is exactly at the top (or if that's not possible, scrolled as far down as it can so it's visible).

Brian Barrett