6

I have a long list of nested divs. I am passing the ID of a particular element (actually a paragraph element) on the querystring and opening its div and parent onload. However, the list is so long, sometimes the element that opens is hidden below the bottom of the window.

How do I automatically scroll the user's browser window so that the displayed element is at the top of the screen?

You probably don't need this, but for the record... my list looks like this:

<div id="div1">
    <p id="1"></p>   
    <div>stuff</div>
    <p id="2"></p>   
    <div>stuff</div>
    <p id="3"></p>   
    <div>stuff</div>
</div>
...
<div id="divN">
    <p id="997"></p>   
    <div>stuff</div>
    <p id="998"></p>   
    <div>stuff</div>
    <p id="999"></p>   
    <div>stuff</div>
</div>
Bryan
  • 8,748
  • 7
  • 41
  • 62

3 Answers3

13

You could use the scrollIntoView function.

$(document).ready(function() {
  $('#divN').get(0).scrollIntoView();
});
nxt
  • 1,983
  • 12
  • 13
  • +1 on this answer, but with the caveat that it does not scroll if the target is already in view. @Russ - This is widely supported to my knowledge. – user113716 Jul 12 '10 at 19:38
  • @Russ: I don't think so, otherwise it would be a pretty nice feature. But I really think it sounds to good to be true. Resig & jQuery core team would have implemented it if its crossbrowser. – jAndy Jul 12 '10 at 19:39
  • 1
    @Russ although it is non-standard it does seem to work in at least IE 5.5+ Firefox, Chrome and Safari. http://www.quirksmode.org/dom/w3c_cssom.html#t23 – nxt Jul 12 '10 at 20:00
6

jQuery:

$(document).ready(function(){
   $(document.body).scrollTop($('#divN').offset().top);
});
jAndy
  • 231,737
  • 57
  • 305
  • 359
2

The easiest way to do this is by using Ariel Flesler's scrollTo plugin. I've used it a few times before and it is small, lightweight and works very well.

Russ Cam
  • 124,184
  • 33
  • 204
  • 266