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 the 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 the button click
  • Set focus to the top of a page
  • scroll to the top of a div There are multiple ways to achieve this.

Set Focus to the top page using plain vanilla javascript

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

Syntax:

window.scrollTo(x - coordinate, y - coordinate);
or;
window.scrollTo(options);

Parameters: x-coordinate is the horizontal or x-axis pixel y-coordinate 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.

window.scrollTo(0, 0);

The above can be rewritten in the shorter form

window.scrollTo(0);

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.

Below code using jquery

<script>
$(document).ready(function(){
   $(window).scrollTop(0);
});
</script>

(or)
$(document).scrollTop(0);

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

window.scroll({
  top: 0,
  left: 0,
  behavior: "smooth",
});

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

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

Here is an example of setting a focus

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

$("#somecontrolontopofpage")[0].scrollIntoView();

Conclusion

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