72

I have a simple page setup such as:

<div id="aboutUs">
  About us content...
</div>
<div id="header">
  Header content...
</div>

When the page loads, I need the page to automatically scroll down (no animation needed) to #header, so the user cannot see the About Us div unless they scroll up.

#aboutUs has a fixed height, so there isn't any need for any variables to determine the height or anything... if that's even needed.

I came across this other question and tried to modify some of the answers for my situation, but nothing seemed to work.

Any help would be appreciated.

Community
  • 1
  • 1
scferg5
  • 2,003
  • 5
  • 22
  • 28
  • Answer to related question here: http://stackoverflow.com/questions/2905867/how-to-scroll-to-specific-item-using-jquery – solveig Jan 16 '12 at 18:12

3 Answers3

131

Description

You can do this using jQuery's .scrollTop() and .offset() method

Check out my sample and this jsFiddle Demonstration

Sample

$(function() {
    $(document).scrollTop( $("#header").offset().top );  
});

More Information

Mark Cooper
  • 6,738
  • 5
  • 54
  • 92
dknaack
  • 60,192
  • 27
  • 155
  • 202
  • Thanks for your answer... it's exactly what I need except I can't get it to work on my end. If it makes any difference, I'm working with a pre-coded storefront (so I can't change the structure) and the About Us div is placed before the header using the .insertBefore method. Would that be causing it not to work? Thanks. – scferg5 Jan 16 '12 at 18:19
  • Sorry for my late respone, i was in the kitchen ;) It looks like you are new to jQuery, right ? You have to wait till the DOM is fully builded. My answer and fiddle is updated. Hope this helps, if not ask me again. – dknaack Jan 16 '12 at 18:38
  • Maybe I'm missing something, but why is this better than `document.getElementById("header").scrollIntoView()`? – Casey Aug 04 '14 at 18:01
27

Did you tried JQuery's scrollTo method? http://demos.flesler.com/jquery/scrollTo/

Or you can extend JQuery and add your custom mentod:

jQuery.fn.extend({
 scrollToMe: function () {
   var x = jQuery(this).offset().top - 100;
   jQuery('html,body').animate({scrollTop: x}, 400);
}});

Then you can call this method like:

$("#header").scrollToMe();
Naveed
  • 11,057
  • 2
  • 44
  • 63
18

Put this right before the closing Body tag at the bottom of the page.

<script>
    if (location.hash) {
        location.href = location.hash;
    }
</script>

jQuery is actually not required.

Chris Pietschmann
  • 29,502
  • 35
  • 121
  • 166