34

Is there a way (with CSS3, JS, or anything in between) to get a page to start at a certain point scrolled down?

I'd like for my page to load without the header initially displaying on load (meaning it's above the actual viewport of the user).

Is there a simple/easy way to go about this?

pb2q
  • 58,613
  • 19
  • 146
  • 147
aroooo
  • 4,726
  • 8
  • 47
  • 81

13 Answers13

34

You can use standard javascript: window.scroll(x, y).

This should work pretty well considering that you'll be doing this at onload, i.e. the window should begin at (0, 0). Play around with (x, y) until you get your header to the position that you're happy with. Naturally you'll need to change it anytime the header moves.

Example:

<body onLoad="window.scroll(0, 150)">
pb2q
  • 58,613
  • 19
  • 146
  • 147
  • In Chrome version 80.x I cannot get this to work with the onload event. It only works when I assign the behavior to a button that the user clicks. Is it a security issue? – posfan12 Feb 11 '20 at 00:02
  • I've been searching forever. Thank you kind sir/madam :) – MatthewSzurkowski Dec 19 '20 at 00:03
  • @MatthewSzurkowski happy that this helps, but note that there are probably much better ways to do this these days, rather than relying on potentially hardcoding pixel values as in the example here in my answer. It depends on your needs, but a) if you're using a specific modern front-end framework, the framework probably has a better way to do this; b) in any case I'd recommend using the position of a known DOM element (something else on the page) relative to what you're trying to show rather than a hardcoded pixel value. – pb2q Dec 19 '20 at 19:49
24

HTML/DOM Solution

If you have an id given to a div that contains your content after the header, then you can probably load the page with a URL of this kind, http://website.com/page#id.

This will take you to the point where the div is present.

Javascript Solution

You can use window.scroll(x,y) on page load.

Lazerbeak12345
  • 309
  • 4
  • 19
Aniket
  • 9,622
  • 5
  • 40
  • 62
  • This helped me out. Thanks! – jimmyplaysdrums Jun 10 '15 at 20:20
  • 4
    Your first solution is an HTML or DOM solution. It has nothing to do with CSS. – David Aug 04 '17 at 17:38
  • 1
    @David The accepted answer is a JS solution and the question doesn't specify a CSS only solution for this. – Aniket Aug 04 '17 at 17:51
  • 5
    You misunderstand. Perhaps I should have just edited your answer, but all I am doing is criticizing the heading you gave to your first solution — not the solution itself. You entiitled it "CSS Solution" but it should be entitled "HTML Solution" or "HTML/DOM Solution" because it does not involve CSS. The fact that it uses an id means it uses the DOM, but you don't have to have a style associated with the id for it to work. – David Aug 04 '17 at 20:11
13

The current answers result in a noticeable "jump" down the page, or require you to know the exact pixel number you want to jump.

I wanted a solution that jumps past a container, regardless of the size/contents of the container, and here's what I came up with:

HTML

<div class="skip-me">Skip this content</div>

CSS

// Hide the content initially with display: none.
.skip-me {
  display: none;
}
.unhide {
  display: block;
}

JS

// Unhide the content and jump to the right place on the page at the same time
function restoreAndSkipContent() {
  var hidden = document.querySelector('.skip-me');

  hidden.classList.add('unhide');
  window.scroll(0, hidden.offsetHeight);
};
restoreAndSkipContent();

Working Demo Here

bryanbraun
  • 3,025
  • 2
  • 26
  • 38
  • I find this code extremely useful, thank you for sharing!, why it didn’t work on mobile (Safari/Crome)? @bryanbraun –  Aug 29 '18 at 11:46
  • It looks like iOS might require something like a setTimeout to run the scroll instruction to the top of the stack. See https://stackoverflow.com/a/19929617/1154642 and https://hackernoon.com/understanding-js-the-event-loop-959beae3ac40 – bryanbraun Aug 29 '18 at 16:17
  • Tried, didn’t work, the scroll still is at top of the page @bryanbraun –  Aug 29 '18 at 19:32
11

These are very simple tricks for that:

  1. Create css offset class and assign to the body

    .offset{
         margin-top:-500px;
        }
    

    So that body will be loaded with 500px offset from top

  2. Then add following code to the body

    <body class="offset" onLoad="window.scroll(0, 150)">
    
  3. then using jquery, remove offset class when page is loaded

    $(document).ready(function(){
       $(".row").removeClass("offset");
    });
    
pb2q
  • 58,613
  • 19
  • 146
  • 147
Uday Hiwarale
  • 4,028
  • 6
  • 45
  • 48
  • That worked better than the other ones! The user doesn't notice the scroll at all with this solution, while with the `` the page scrolls when load is completed which is annoying for the users. – Alberto Fontana Feb 12 '15 at 22:11
  • 1
    Although that `offset` class should probably only be added via JS in the first place – otherwise, when JS is not available the `margin-top:-500px` will stay in place and will make the first 500 pixels of content unreachable by scrolling … (And using vanilla JS and “old-school” event handling for the scrolling, but then jQuery for the class removal doesn’t make the most sense either – why not both the same way?) – CBroe Feb 14 '15 at 14:04
  • @CBroe I think I tried that, but didn't work for me. `when JS is not available the margin-top:-500px will stay in place and will make the first 500 pixels of content unreachable by scrolling`, that's the way it is. See 500px profile for example. – Uday Hiwarale Feb 14 '15 at 21:03
7

HTML - Named anchors

You can also make use of good old anchors. Define a named anchor using

     <a id="start">any text</a>

This should be defined at the point that has to be in view. As it can be in view even at the bottom of the screen, you might have to give anchor a little below than required. That way we will make sure that contents on top that need not be shown are well hidden. Once it is defined to scroll down when the page gets loaded, URL should be page.aspx#start instead of page.aspx

<a href="#start">access within the same page</a>

<a href="page.aspx#start">access from outside the page</a>
Anuradha Kulkarni
  • 259
  • 1
  • 3
  • 11
2

Using javascript scrollBy. For this method to work, the visible property of the window's scrollbar must be set to true. So make sure you page is long enough for the vertical scrollbar to appear.

<html>
<head>
</head>
<body onLoad="window.scrollBy(0,100)">
     <div style="height:300px;"> Some text </div>
     <div style="height:900px;"> Some text 2 </div>
</body>
</html>
astro boy
  • 1,410
  • 1
  • 11
  • 16
2

Use Javascript window.scroll:

$(window).scroll(function(){ 
  if ($(this).scrollTop() > 100){ 
    $('something').hide();
  } 
  else{
      $j('something').show();

  }
});​
pb2q
  • 58,613
  • 19
  • 146
  • 147
SVS
  • 4,245
  • 1
  • 23
  • 28
1

This work to me.

<div class="demo">
        <h2>Demo</h2>
</div>


<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
    <script>
        $(document).ready(function () {
            $('html, body').animate({
                scrollTop: $('.demo').offset().top
            }, 'slow');
        });
    </script>

Thanks.

Y. Joy Ch. Singha
  • 3,056
  • 24
  • 26
0

there is a function in jquery called .scroll().. You can use that function to make your header visible only when user scrolls the site..

Jigar Jain
  • 1,447
  • 1
  • 15
  • 38
0

The Combined Solution

Every single JavaScript-first solution may (and usually does) lead to a hiccup before the pageLoad event. As Uday suggested, the best way to achieve seamless scrolled load is to employ the negative css margin.

Personally, I use a code snippet similar to the one of Uday, however slightly tweaked to make it work in browsers without JavaScript and not to repeat the scroll declaration.

<!doctype html>
<html>
<head>
    <style>
        /* Can be in an external stylesheet as well */
        /* This is the ONLY place where you will specify the scroll offset */
        BODY.initialoffset {margin-top: -100px; /* Or whatever scroll value you need */}
    </style>
    <noscript>
        <!-- Browsers without JavaScript should ignore all this margin/scroll trickery -->
        <style>
            BODY.initialoffset {margin-top: initial; /* Or 0, if you wish */}
        </style>
    </noscript>
</head>
<body onLoad = "(function(){var B=document.getElementsByTagName('body')[0],S=B.currentStyle||window.getComputedStyle(B),Y=parseInt(S.marginTop);B.className=B.className.replace(/\binitialoffset\b/g,'');window.scroll(0,-Y);})()">
</body>
</html>

The short self-calling function in the onLoad attribute can be expanded as follows:

(function(){
    /* Read the marginTop property of the BODY element */
    var body=document.getElementsByTagName('body')[0],
        style=body.currentStyle||window.getComputedStyle(body),
        offsetY=parseInt(style.marginTop);
    /* Remove the initialoffset class from the BODY. (This is the ugly, but everywhere-working alternative)... */
    body.className=body.className.replace(/\binitialoffset\b/gi,'');
    /* ...and replace it with the actual scroll */
    window.scroll(0, -offsetY);
    })()
Pavel Říha
  • 51
  • 1
  • 2
0

I found @bryanbraun's suggestion very useful. I found that removing the window.scroll produces a nice effect for hiding a nav bar. I've simply added this to the head of my doc:

      <script>
        function restoreSkippedContent() {
          var hidden = document.querySelector('.onScrollHide');

          hidden.classList.add('unhide');
          // window.scroll(0, hidden.offsetHeight);
        };
      </script>
      <style>
        .onScrollHide {
          display: none;
        }
        .unhide {
          display: unset !important;
        }
      </style>

and then added a wrapper around my nav bar and an onscroll trigger rather than an onload:

<body onscroll="restoreSkippedContent()">
  <div class="navBarContainer onScrollHide">
    <nav> .... </nav>
  </div>
  ...
</body>

This the nice effect of not causing any interruption to the user, but when they scroll up they see the nav bar :)

It's currently in use here

Alex Morris
  • 633
  • 5
  • 16
0

I had the exact same problem mentioned in the question :

"I'd like for my page to load without the header initially displaying on load"

I'm not a Javascript guru but I think I found a clever way of doing this, as the other answers did not satisfy me with the end result. Here's my way:

CSS :

#header {display:none}

JS :

window.onscroll = function() {document.querySelector('#header').style.display = "block"}
window.onload = function () {window.scrollTo({top: 1,behavior: 'smooth'})}   

Here is a video preview on a website I run.

It's perfect to me. The 1 pixel scroll down is really not a deal breaker imho, almost impossible to notice, and allows to be able to scroll top directly.

Max
  • 169
  • 2
  • 11
0
    function ScroolPositionButtom() {
    var elment = document.querySelector(".right .chat.active-chat");
    elment.scrollTo(0, elment.scrollHeight);
}

This is work for me. I use this function for a specific class.