简体   繁体   中英

How can I scroll to the top of a page using Javascript?

How to scroll to top of the page in php with javascript

scroll(0,0); \\ this is not working?

On click of submit, i call a function to validate the form and incase of error i will be setting the errormessage thru innerhtml and need to scroll to top of the page without submitting.

Everything works...but its not scrolling to top of the page

使用窗口属性 scrollTop ( MSDN , MDC ) 设置要滚动偏移的像素数。

window.scrollTop = '0';

If you have a particular element that you want to scroll over, lets say, the element of whose innerHTML you are modifying then you can use the following

 element.scrollIntoView(true);

Works in all browsers

How about trying window.scrollTo(0,0). It is basically the same thing as scroll(0,0).

If it does not work, show us more code.

Scrolling to the absolute top of the page can be achieved by either

window.scrollTo(0,0);

or

window.location = "#";

Note that the second method will append "#" to the current URL.

<a href="#">Scroll to Selected Position</a>

Above code worked for me. I tried with onclick="window.scrollTo(0, 0);" but this does not worked for me, all I needed was href="#" and no onclick. We might also notice that # will be getting appended in url .

Old non-working code has href="javascript:scroll(0,0)" which had an issue in doing scroll to top in angular/iframe component.

Above code does not worked in Firefox.

Final Solution:

function scrollToSelectedPosition() {
   var sectionToJump = document.getElementById('section-to-jump');
   $(sectionToJump).scrollIntoView();
}

and

<a onclick="scrollToSelectedPosition()">Scroll to Selected Position</a>

This worked in FireFox, Chrome, Safari and IE.

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