A Web Component to add anchor links to headings with IDs.
<script type="module" src="heading-anchors.js"></script>
<heading-anchors>
<h2 id="heading-level-2">Heading level 2</h2>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit.</p>
<h3 id="heading-level-3">Heading level 3</h3>
<p>
Excepturi eligendi exercitationem, ratione, in delectus vitae veritatis
dolorem porro cupiditate quam eaque voluptates.
</p>
</heading-anchors>
This Web Component allows you to:
- Add anchor links to headings which have an ID attribute and value
- Customise which elements will be appended with an anchor link using the
selector
attribute - Customise where the anchor link is appended using the
position
attribute
You have a few options (choose one of these):
- Install via npm:
npm install @daviddarnes/heading-anchors
- Download the source manually from GitHub into your project.
- Skip this step and use the script directly via a 3rd party CDN (not recommended for production use)
Make sure you include the <script>
in your project (choose one of these):
<!-- Host yourself -->
<script type="module" src="heading-anchors.js"></script>
<!-- 3rd party CDN, not recommended for production use -->
<script
type="module"
src="https://www.unpkg.com/@daviddarnes/heading-anchors@2.0.0/heading-anchors.js"
></script>
<!-- 3rd party CDN, not recommended for production use -->
<script
type="module"
src="https://esm.sh/@daviddarnes/heading-anchors@2.0.0"
></script>
By default heading-anchors
will select all the h2[id]
, h3[id]
and h4[id]
elements within it to append an anchor link to. However with the selector
attribute you can pass in a different selector string to select:
<heading-anchors selector="h2[id]">
<!-- ... -->
</heading-anchors>
Note: It's recommended you use selectors that utilise the [id]
attribute selector for better reliability
By default heading-anchors
will append anchor links right after the element, using the insertAdjacentHTML
API. However you can adjust this using the position
attribute:
<heading-anchors position="beforeend">
<!-- ... -->
</heading-anchors>
With thanks to the following people:
- Zach Leatherman for inspiring this Web Component repo template
- Curtis Wilcox for the accessibility feedback