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!