Home > Article > Web Front-end > How Can I Use JavaScript to Navigate to an HTML Anchor?
To enhance the user experience, it's often desirable to navigate to a specific section of a web page by clicking an anchor link. This can be seamlessly achieved with JavaScript, even without relying on external libraries like jQuery.
Anchor links are typically defined in HTML using the name or id attributes:
<a name="anchorName">...</a>
or
<h1>
To scroll the page to the desired anchor, simply set the hash property of the location object:
function scrollTo(hash) { location.hash = "#" + hash; }
For instance, to navigate to the anchor named "anchorName", call the scrollTo() function as follows:
scrollTo("anchorName");
This will seamlessly scroll the page to display the anchor near the top of the visible area.
The above is the detailed content of How Can I Use JavaScript to Navigate to an HTML Anchor?. For more information, please follow other related articles on the PHP Chinese website!