Heading Anchors
Add anchor links to all of the headings inside a container element, with a visible icon.
Usage
Wrap the content that should have heading links in the <kelp-heading-anchors> element.
All of the h2 through h6 elements within it will get wrapped in a link, with a hash icon (#) appended, like the headings on this page. If the heading does not have an ID, one will be dynamically generated.
<kelp-heading-anchors>
	<h2>Usage</h2>
	...
	<h2>Options</h2>
	...
	<h2>Events</h2>
	...
</kelp-heading-anchors>Options
Use custom attributes to configure component settings.
- [icon]- The icon to display next to the heading (default:- #).
- [levels]- The heading levels to target (default:- h2, h3, h4, h5, h6).
- [before]- If present, the icon is displayed before the text instead of after.
<kelp-heading-anchors
	icon="🎉"
	levels="h2"
	before
>
	<!-- ... -->
</kelp-heading-anchors>Styling
The <kelp-heading-anchors> component adds four classes:
- .anchor-h- The heading element.
- .anchor-link- The generated- <a>element.
- .anchor-text- The heading text.
- .anchor-icon- The icon element.
<h2 class="anchor-h" id="merlin">
	<a class="anchor-link" href="#merlin">
		<span class="anchor-text">Merlin</span>
		<span class="anchor-icon">#</span>
	</a>
</h2>The .anchor-link class is styled to inherit the color of the parent heading with no underline rather than look like a link.
The .anchor-icon uses the --color-text-link and --color-text-link-hover CSS variables for its color. On :hover, it uses the --decoration-text-link-hover CSS variable for it’s text-decoration property.
.anchor-link {
	--color: inherit;
	--color-hover: inherit;
	--decoration: none;
	--decoration-hover: none;
}
.anchor-icon {
	color: var(--color-text-link);
}
.anchor-link:hover .anchor-icon {
	color: var(--color-text-link-hover);
	text-decoration: var(--decoration-text-link-hover);
}If the [before] attribute is used, the .anchor-link receives a text-indent property of -1em on larger viewports.
This shifts the icon off to the side, keeping the heading lined up with the text.
Events
The <kelp-heading-anchors> element emits a kelp-heading-anchors:ready event once anchor links have been added to the headings.
document.addEventListener('kelp-heading-anchors:ready', (event) => {
	console.log('ready:', event.target);
});
Methods
While web components are self-instantiating, the <kelp-heading-anchors> element can be manually initialized with the .init() method if it fails for some reason.
const headingAnchors = document.querySelector('kelp-heading-anchors');
headingAnchors.init();