Home >Web Front-end >JS Tutorial >How to Smoothly Scroll to the Bottom of a Page with jQuery?

How to Smoothly Scroll to the Bottom of a Page with jQuery?

Susan Sarandon
Susan SarandonOriginal
2024-12-21 05:33:14964browse

How to Smoothly Scroll to the Bottom of a Page with jQuery?

Scroll to an Element with jQuery: Animate Smoothly to the Bottom of the Page

This article explores a technique for smoothly scrolling a web page to the last element using the latest version of jQuery, without relying on external plugins.

Problem:

Consider the following HTML structure:

<input type="text">

The objective is to automatically scroll the page to the submit button, with a fluid animation, when the user clicks on the text input with the id "subject."

Solution:

To achieve this, we can leverage the animate() method in jQuery. Here's an example code snippet:

$("#subject").click(function() {
    $([document.documentElement, document.body]).animate({
        scrollTop: $("#submit").offset().top
    }, 2000);
});

This code:

  1. Selects the input element with the id "subject" using jQuery.
  2. Attaches a click event handler to the input element.
  3. Within the event handler, it animates the scrolling of the document, which includes both HTML and body elements, to the offset top of the submit button with an id "submit."
  4. Specifies the animation duration as 2000 milliseconds for a smooth experience.

This code ensures that when the user clicks on the input element, the page smoothly scrolls to the last element, providing an enhanced user experience.

The above is the detailed content of How to Smoothly Scroll to the Bottom of a Page with jQuery?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn