Home > Web Front-end > JS Tutorial > How to Scroll to Specific Anchors on a Web Page using JavaScript?

How to Scroll to Specific Anchors on a Web Page using JavaScript?

Mary-Kate Olsen
Release: 2024-11-17 18:39:02
Original
435 people have browsed it

How to Scroll to Specific Anchors on a Web Page using JavaScript?

Navigating Web Pages to Specific Anchors using JavaScript

Navigating a web page to a specific anchor can be achieved with JavaScript by utilizing the location.hash property. Anchors are specified in HTML using the name or id attributes.

Code:

The following JavaScript code provides a simple solution to scroll the page to a given anchor:

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

Usage:

This function takes a single parameter, hash, which corresponds to the name or id of the anchor. Calling scrollTo('anchorName') will scroll the page to the element with the specified anchorName.

Example:

In the following HTML structure:

<html>
<body>
    <a name="section1">...</a>
    <a name="section2">...</a>
</body>
</html>
Copy after login

Calling scrollTo('section2') would smoothly scroll the page to the section with the section2 anchor. This mimics the effect of directly accessing the URL http://server.com/path#section2, ensuring the anchor is visible near the top of the page.

Note:

This method does not require jQuery or any additional libraries and works effectively on various browsers.

The above is the detailed content of How to Scroll to Specific Anchors on a Web Page using JavaScript?. 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