简体   繁体   中英

Scroll to top of an element without using animate

HOw can I scroll to top of an element without using animate()? I googled, but all answers are with animate().

$("#button").click(function() {
    $('html, body').animate({
        scrollTop: $("#elementtoScrollToID").offset().top
    }, 2000);
});

I just want to instantly go to the top of an element. In my case, the animate() is not necessary.

Use .scrollTop()

 $("#button").click(function() { $('html, body').scrollTop( $("#elementtoScrollToID").offset().top); }); 
 .dummy { height: 1200px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <button id="button">Test</button> <div class="dummy"></div> <div id="elementtoScrollToID">elementtoScrollToID</div> 

You can do it just passing an anchor, pure HTML:

<a href="#top">go to top</a>

and you just add an <a name="top"></a> on the top of your website :)

You achieve the same affect without jQuery by using Window.scroll()

 document.getElementById("button").onclick = function() { window.scroll(0,document.getElementById("elementtoScrollToID").offsetTop); }; 
 <button id="button">Button</button> <div id="elementtoScrollToID" style="margin: 800px 0;"> Scroll to here... </div> <!-- jQuery --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

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