views:

350

answers:

5

What I want to do is scroll down the window when I expand elements in my page.

The effect I am trying to achieve is like the Stack Overflow comments. If it expands beyond the page, it scrolls down to fit all the comments in the window.

What is the best way of doing this?

Edit: I am using JQuery.

A: 

If you have the advantage of using Prototype, you can use $(element).scrollTo().

Otherwise, the general idea is to calculate the cumulative offset of the element, then set window.scrollTop (and window.scrollLeft) accordingly.

eyelidlessness
A: 

You can do it nicely with Scriptaculous (built on top of Prototype):

new Effect.ScrollTo('someDiv',{...some parameters...})

It gives you finer control than Prototype alone (delay before start, duration and callback events (such as afterFinish) that allow you to trigger other effects or whatever you choose. You can make it scroll smoothly and nicely, so the page doesn't suddenly jump.

Diodeus
+1  A: 

This jQuery plugin worked well for me: http://demos.flesler.com/jquery/scrollTo/

Joe W.
A: 

If you know what the next element in the source is you could actually just jump to that element (location.href="#..."). This would use the browser's native 'scrolling' and not use any libraries.

A: 

You could use this code wich is okay but not perfect. Based on the suggestion by blonkm

function scrollTo( Selector ){
  $(Selector).before("<a name='scroll' id='scroll'></a>");
  document.location.hash = 'scroll';
  $('scroll').remove();
}

This should work. Requires jQuery but you already say your using that.

Pim Jager