How to set focus on top page in angular|javascript example

Consider a page with a long user form and a submit button that supports vertical scrolling. When a user presses the submit button, the server performs validation, and any errors must be present to the user.

if the error displays on top of the page, the user needs to scroll to the top to see what error occurred.

Instead, If errors are displayed and moving focus to the top of the page is a good experience during a button click.

This post explains how to set focus on the start or top of the page in javascript and angular.

This post solves some of the problems

  • jump to the top of the browser page
  • force scroll to the start of a page on button click
  • Set focus to the top of a page
  • scroll to the top of a div There are multiple ways to achieve this.

using plain vanilla javascript

window object provides scrollTo function which scrolls cursor to coordinates of a page.

** Syntax:**

window.scrollTo(x-cordinate,y-coridate); (or)

parameters: x-cordinate is the horizontal or x-axis pixel y-coridate is the vertical or y-axis pixel

** Options** is javascript object of type ScrollToOptions - which contains top,left and behavior

for example, to move to the top of the page.


The above can rewritten with shorter form


if you want to add smooth animations, Here is an example

window.scrollTo({ top: 0, behavior: 'smooth' });

javascript to scroll to a page on a button click

Suppose we have a long page with content.




How to move the cursor to the top of the page in typescript

      top: 0,
      left: 0,
      behavior: 'smooth'

How to set focus to div element on button click submit with javascript?

Usually, input elements like textbox, radio, and checkboxes have an inbuilt focus element.

Here is an example for setting focus

$('#myform').on('submit', function() {
  $('html, body').animate({scrollTop:0}, 'slow');



You learned how to scroll on a long page with content with an example in javascript.

Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
You'll get a notification every time a post gets published here.