Skip to content

Commit

Permalink
feat: header anchors
Browse files Browse the repository at this point in the history
  • Loading branch information
comfysage committed Jan 15, 2025
1 parent 1b8e25c commit f6c9d65
Showing 1 changed file with 30 additions and 0 deletions.
30 changes: 30 additions & 0 deletions templates/pages/post.tera
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,9 @@
</section>

<div id="comments"></div>
{% endblock %}

{% block additionalfoot %}
<script>
const codeblocks = document.querySelectorAll('div.codeblock');

Expand Down Expand Up @@ -150,4 +152,32 @@
comments.appendChild(script);
};
</script>

<script>
function create_anchor(elem) {
let anchor_id = elem.textContent.toLowerCase().replaceAll(/[^a-z0-9]/g, '-')
elem.id = anchor_id

let header_elem = document.createElement('div')
header_elem.classList.add('anchor')

let anchor_elem = document.createElement('a')
anchor_elem.href = `#${anchor_id}`
anchor_elem.classList.add('anchor')

const range = document.createRange();
range.selectNode(elem)
range.surroundContents(header_elem);

header_elem.appendChild(anchor_elem)
return header_elem
}

window.addEventListener('load', () => {
let prose = document.querySelector("article.prose")
for (let i = 2; i <= 6; i++) {
prose.querySelectorAll(`h${i}`).forEach(create_anchor)
}
});
</script>
{% endblock %}

0 comments on commit f6c9d65

Please sign in to comment.