Home > Web Front-end > CSS Tutorial > How to Smoothly Scroll to a Specific Element Using jQuery Animation on Button Click?

How to Smoothly Scroll to a Specific Element Using jQuery Animation on Button Click?

Barbara Streisand
Release: 2024-10-31 01:24:29
Original
797 people have browsed it

How to Smoothly Scroll to a Specific Element Using jQuery Animation on Button Click?

Animate Scroll to Specific Element on Button Click

To jump or scroll to a specific position, div, or target on a page when a button is clicked, you can employ jQuery's animation capabilities.

HTML Structure:

Create a button element with an id or class for referencing it in JavaScript. Also, set up the target element with an id to be scrolled to.

JavaScript:

<code class="javascript">$('#clickMe').click(function() {
    $('html, body').animate({
        scrollTop: $('#targetElement').offset().top
    }, 600);
});</code>
Copy after login
Copy after login

In this script, when the #clickMe button is clicked, it triggers the animation of the html and body elements to scroll to the top offset of the #targetElement. The 600 parameter sets the duration of the animation in milliseconds.

Example:

Consider the following HTML structure:

<code class="html"><a id="clickMe" href="#">Go to Div</a>

<div id="targetElement">Target Div</div></code>
Copy after login

The corresponding JavaScript:

<code class="javascript">$('#clickMe').click(function() {
    $('html, body').animate({
        scrollTop: $('#targetElement').offset().top
    }, 600);
});</code>
Copy after login
Copy after login

When the "Go to Div" button is clicked, the page will smoothly scroll to the "Target Div" element.

The above is the detailed content of How to Smoothly Scroll to a Specific Element Using jQuery Animation on Button Click?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template