Home > Web Front-end > JS Tutorial > How to Scroll to a Specific Anchor on an HTML Page Using JavaScript?

How to Scroll to a Specific Anchor on an HTML Page Using JavaScript?

Susan Sarandon
Release: 2024-11-15 15:48:03
Original
463 people have browsed it

How to Scroll to a Specific Anchor on an HTML Page Using JavaScript?

Scrolling to a Specific Anchor on an HTML Page

JavaScript provides a convenient way to scroll an HTML page to a particular anchor, allowing for seamless navigation within the document.

Problem:

You want to scroll the browser's page to a given anchor when a button is clicked or a specific event occurs. The target anchor can have a name attribute or an id attribute.

Answer:

The following JavaScript function allows you to achieve this functionality:

Implementation:

To use this function, simply call it with the anchor's name or ID as a parameter. For example, if you have an anchor with an ID of "myAnchor," you would call the function as follows:

This technique takes advantage of the fact that the location.hash property is automatically updated when the browser scrolls to an anchor. By setting the location.hash to the desired anchor, you force the browser to scroll to that location.

Note:

No external libraries (such as jQuery) are required to implement this functionality. It works natively in all major browsers.

The above is the detailed content of How to Scroll to a Specific Anchor on an HTML 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