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
Barbara StreisandOriginal
2024-10-31 01:24:29767browse

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>

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>

The corresponding JavaScript:

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

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!

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