How can I smoothly scroll to the submit button after clicking an input element?

I have an <input> element with id subject and other elements on the page. When the user clicks the <input>, I want the page to smoothly scroll to the last element, which is a submit button with id submit. I’m using the latest Jquery scroll to element version and prefer not to install additional plugins.

Hey MattD,

If you have a button with the id button, you can use this example:

$(“#button”).click(function() { $([document.documentElement, document.body]).animate({ scrollTop: $(“#elementtoScrollToID”).offset().top }, 2000); });

This code snippet is adapted from the article “Smoothly scroll to an element without a jQuery plugin” available here (Smoothly scroll to an element without a jQuery plugin).

Hey MattD

You can achieve this without jQuery:

document.getElementById(“element-id”).scrollIntoView(); This native JavaScript method scrolls the page to the element with the specified id.

Hey MattD,

Here’s a straightforward approach using native JavaScript that works across different browsers:

document.querySelector(‘scrollHere’).scrollIntoView({ behavior: ‘smooth’ });

This code smoothly scrolls the page to the element specified by the selector ‘scrollHere’.

For reusability, you can wrap this functionality into a function: function scrollTo(selector) { document.querySelector(selector).scrollIntoView({ behavior: ‘smooth’ }); }

Now, you can call scrollTo with any valid CSS selector to smoothly scroll to the corresponding element.