0

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

Liam
  • 27,717
  • 28
  • 128
  • 190
ASD
  • 4,747
  • 10
  • 36
  • 56

5 Answers5

5

Use window property scrollTop (MSDN, MDC) to set number of pixels to scroll offset.

window.scrollTop = '0';
nemisj
  • 11,562
  • 2
  • 25
  • 23
3

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

jmishra
  • 2,086
  • 2
  • 24
  • 38
1

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.

epascarello
  • 204,599
  • 20
  • 195
  • 236
1

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.

Justin Johnson
  • 30,978
  • 7
  • 65
  • 89
0
<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.

Manish Kumar
  • 191
  • 1
  • 9