What is an 'anchor' in the context of web development?
sobes.tech AI
Answer from AI
A anchor in web development is an identifier (HTML attribute id) of an element on a page, allowing to create a link to a specific place within the same or another HTML page. When clicking such a link, the browser scrolls the page to the element with the specified anchor.
<a href="#section2">Go to the second section</a>
<h2 id="section2">Second Section</h2>
Anchors are also used to form URLs with fragment identifiers, for example: https://example.com/page#section2.
In addition to manually setting the id attribute, many browsers automatically create anchors for headings (<h1> - <h6>) when hovered or focused, which is convenient for creating links to content sections.
Typical use cases:
- Navigation within long pages (single-page applications, articles).
- Creating a table of contents with clickable items.
- Direct links to specific content sections from external sources.
Technically, the anchor is processed by the browser on the client side, without a request to the server, if the link points to the same page.
// Getting an element by anchor from URL
const anchorId = window.location.hash.substring(1); // Remove the '#' symbol
if (anchorId) {
const targetElement = document.getElementById(anchorId);
if (targetElement) {
// You can use smooth scrolling
targetElement.scrollIntoView({ behavior: 'smooth' });
}
}