Skip to content

Commit d5eecd6

Browse files
committed
Enhance title stickiness
1 parent 66219f2 commit d5eecd6

File tree

2 files changed

+37
-1
lines changed

2 files changed

+37
-1
lines changed

src/components/app/Title.astro

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
---
2+
const { title } = Astro.props;
3+
---
4+
5+
<!-- to stick to the header -->
6+
<div
7+
data-stuck-small
8+
class="sticky -top-1 z-30 h-0 opacity-0 transtion-duration-300 transition-opacity"
9+
>
10+
<h5 class="absolute mt-5 text-sm ml-30">
11+
{title}
12+
</h5>
13+
</div>
14+
15+
<!-- persistent one -->
16+
<h1 class="text-3xl sm:text-4xl mb-3">
17+
{title}
18+
</h1>
19+
20+
<!-- thanks to https://davidwalsh.name/detect-sticky -->
21+
<script>
22+
const el = document.querySelector('[data-stuck-small]');
23+
24+
const observer = new IntersectionObserver(
25+
([e]) => {
26+
el &&
27+
['opacity-100'].forEach((cls) => {
28+
el.classList.toggle(cls, e.intersectionRatio < 1);
29+
});
30+
},
31+
{ threshold: [1] }
32+
);
33+
34+
el && observer.observe(el);
35+
</script>

src/layouts/Post.astro

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
---
22
import Layout from './Layout.astro';
3+
import Title from '../components/app/Title.astro';
34
import { format } from '../lib/date';
45
import { links } from '@lib/links';
56
@@ -36,7 +37,7 @@ const formattedDate = dates.map((date, idx) => `${prefixes[idx]} ${date}`).join(
3637
<Layout title={title}>
3738
<!-- .prose seems to with weird gap without margin so mitigate that with `-my-[n]` -->
3839
<article class="prose -my-3">
39-
<h1 class="sticky top-0 z-10 text-3xl sm:text-4xl mb-3">{title}</h1>
40+
<Title title={title} />
4041
{
4142
!toy && (
4243
<small class="text-slate">

0 commit comments

Comments
 (0)