How to Scroll to the Top in JavaScript


If you have a long web page that requires the user to scroll a lot, your users might enjoy the ability to get back to the top of the page quickly. This will encourage users to scroll down through the page content. This can be accomplished by using the JavaScript "jumpScroll" and "window.scroll" functions, which allows you to specify a point to jump to by using the pixel coordinates of the current window. This script can be triggered with a link and works across all JavaScript-compatible web browsers.

  • Open a web page in a text editor by right-clicking the file and clicking "Open With." Click to select "Notepad."

  • Click to place your text cursor between the "<head>" and "</head>" tags, then press "ENTER" to create a blank line.

  • Type "<script type="text/javascript"> function jumpScroll() { window.scroll(0,0);}</script>" on the blank line. The "0,0" part of the code specifies where you wish to jump to when the user clicks the link. The "0,0" value refers to the pixel coordinates in the top-left corner of the web page.

  • Scroll down to the point in the web page code where you wish to place the link that will scroll back to the top. Click to place your cursor on a blank line, or click and press "ENTER" to create a blank line.

  • Type "<a href="javascript:jumpScroll()">[TOP]</a>" to create a link with the text "[TOP]" that will take the user back to the top of the web page. Replace the "[TOP]" text with the link text of your choice, if desired.

  • Click the "File" menu, then click "Save" to save the web page document.


Promoted By Zergnet


You May Also Like

Related Searches

Is DIY in your DNA? Become part of our maker community.
Submit Your Work!