Scroll Page on Page Load

On loading a web page scroll to the top of a form.

I had a web page with a form, part of a sequence of pages. Rather than the user scrolling down to the start of the form, I scrolled the page to the start of the form on page load.

Or more specifically to scroll to just above the top of the form on page load. Giving a degree of orientation reference within the page.

Above the form I added a div with an id:

<div id=”FormTop”></div>

Within the header (or separate JavaScript file if preferred) add the entry to scroll the page.

$(document).ready(function(){
  $('html, body').animate({scrollTop: $('#FormTop').offset().top}, 'slow');
});

Shown above is the animation, associated with either html or body. Here the scrollTop function moves the page to the FormTop ident, at a speed set as slow. Once the page has completed loading and is ready.

Perhaps the scroll isn’t to your liking. Both the speed and the flow (easing) of the scroll can be changed.

Other speeds can be used, try experimenting with these (in milliseconds):

$(‘html, body’).animate({scrollTop: $(‘#FormTop’).offset().top}, ‘500’);

The easing effects used for the animation can also be added, for example:

$(‘html, body’).animate({scrollTop: $(‘#FormTop’).offset().top}, ‘slow’, ‘swing’);

Linear is an alternative. This specifies how the path of the animation flows. There are more available by incorporating the jQuery UI script.

No doubt when you implement this you’ll add the single action line along with the rest of your items within $(document).ready(function(), not give its own distinct wrapper.

References

https://api.jquery.com/animate/

https://www.w3schools.com/jquery/eff_animate.asp

https://jqueryui.com/easing/