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 presented to the user.

if the error displayed on top of the page,  User needs to scroll to top to see what error occured.

Instead, If errors displayed and move focus to top of page is a good experience during button click

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

This post solves some of problems

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

using plain vanilla javascript

   window object provides scrollTo function which scroll cursor to coordinates of a page.   ** Syntax:**   ```javascript  window.scrollTo(x-cordinate,y-coridate); (or)  window.scrollTo(options)

¬†¬†**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 top of the page. ¬† ¬† ¬†javascript ¬†window.scrollTo(0,0); ¬† ¬†¬†The above can rewritten with shorter form ¬†javascript ¬†window.scrollTo(0) ¬†¬† ¬†if you want to add smooth animations, Here is an example ¬† ¬† ¬† ¬†javascript ¬†window.scrollTo({ top: 0, behavior: ‚Äėsmooth‚Äô }); ¬†```

javascript to scroll to a page on a button click

Suppose we have a long page with    # jquery  ```    $(document).ready(function(){     $(window).scrollTop(0); });

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


How to move cursor to top of page in typescript


window.scroll({
      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 has inbuilt focus element.

if you want to  

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

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


 
 
 
 
 
THE BEST NEWSLETTER ANYWHERE
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
Subscribe
You'll get a notification every time a post gets published here.