Reputation: 759
Is there a way to start the page at certain div without scrolling using jQuery
?
For now i'm using this code:
$('html, body').animate({
scrollTop: $('.here').offset().top
}, 500);
But this, of course, scrolls to that div on page loading, i want it to just load the page straight to that div(if there is a certain cookie set)
Upvotes: 3
Views: 1297
Reputation: 50759
You can run this javascript when the page loads. It will take you to the specified div with the id
specified. Take a look at the snippet below:
let boxTop = $("#orange-div").offset().top;
window.scrollTo(0, boxTop);
.padding-div {
height: 200vh;
width: 200px;
background-color: red;
}
.box {
height: 100px;
width: 200px;
background-color: orange;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="padding-div">
</div>
<div id="orange-div" class="box">
</div>
<div class="padding-div">
</div>
Upvotes: 1
Reputation: 18249
You don't need to use animate
to change the scroll position. Just do $('html, body').scrollTop($('.here').offset().top)
.
Or probably even simpler, just give the desired element an id and then set the window.location.hash
to be that id.
Upvotes: 3
Reputation: 682
"if there is a certain cookie set"
If you're using any server-side scripting language to get/set that cookie, you could also append the id to the div as a hash to make it jump to that div.
So for example, if my page is
....
<div id="somecontent">...</div>
<div id="jumphere">...</div>
<div id="someothercontent">...</div>
...
and the url is http://www.myawesomewebsite.com/page#jumphere, then in most browsers, your page will jump to that point after load
Upvotes: 1
Reputation: 191976
You can use window.scrollTo()
:
const target = $('.here').offset().top;
window.scrollTo({
top: target,
behavior: 'instant'
});
.block {
height: 49vh;
background: red;
margin-bottom: 1vh;
}
.here {
background: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="block"></div>
<div class="block"></div>
<div class="block here"></div>
<div class="block"></div>
Upvotes: 1