I’m currently trying to figure a way to make a website load up and already be scrolled so far down.
For example…
CSS
body {
height:2000px;
}
#red-box {
position:absolute;
width:100%;
height:150px;
background-color:red;
}
#blue-box {
position:absolute;
width:100%;
height:500px;
margin-top:150px;
background-color:blue;
}
HTML
<div id="red-box"></div>
<div id="blue-box"></div>
Is there anyway I can make the webpage already be scrolled down far enough to make the red-box div already be off the top of the page. In other words, the page has already scrolled down 150px (the height of the red-box) when it loads up and in order to see the red-box, the user would have to manually scroll back up.
I’ve tried several JavaScripts but the only one that came remotely close to sort of working was…
JavaScript
$(window).scroll(function(event) {
window.scrollTo(0,150);
});
But that does not do what I need and, in fact, makes the whole page unscrollable- It does scroll down to 150px, but only when the user manually scrolls the page by any ammount, and then it gets stuck there and won’t scroll at all.
I’m not the greatest at JavaScript… I think my problem might have something to do with the
$(window).scroll(function(event) {
});
section. As I think
window.scrollTo(0,150);
is what I actually want it to do. But I’m just guessing here and I can’t seem to get it to work at all.
I’ve created a JSFiddle to try and demonstrate a bit clearer.
Can anyone help me?
You are setting scroll position to 0(,150) on every scroll event which you don’t want. You should do it only on page load. Change it to this code.
To make it perfectly scroll to the red box use this code.
offset()method gives the top/left position of the element relative to the document.