Home >Web Front-end >JS Tutorial >How to Scroll to a Specific Anchor in HTML with JavaScript?

How to Scroll to a Specific Anchor in HTML with JavaScript?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-30 01:30:09994browse

How to Scroll to a Specific Anchor in HTML with JavaScript?

Scrolling an HTML Page to a Specific Anchor using JavaScript

Problem:

Need to programmatically scroll an HTML page to a specific anchor using only JavaScript. You have assigned a name or id attribute to the desired anchor, e.g.:

<a name="anchorName"></a>
<h1>

The goal is to replicate the effect of manually navigating to a URL with an anchor fragment, such as http://server.com/path#anchorName.

Solution:

function scrollTo(hash) {
    location.hash = "#" + hash;
}

This JavaScript function scrolls the page to the anchor by setting the location.hash property. The location.hash property represents the anchor fragment of the current URL. By assigning the desired anchor name to this property, the browser will automatically scroll the page to the appropriate position.

Unlike many other solutions, this method does not require any external libraries like jQuery.

The above is the detailed content of How to Scroll to a Specific Anchor in HTML with JavaScript?. 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