简体   繁体   中英

jQuery start page at certain div without scrolling

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)

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.

" 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

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> 

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM