# useScrollSpy

`useScrollSpy(ids, options)` tracks which section of the page is being read. Use it to
highlight the current item of a table of contents.

The current heading is the last one whose top has passed the `line`. The line is a share of the
window or `root` container height, 0.2 by default, that is a fifth from the top.

```vue
<template>
  <div class="w-full grid-auto gap-6">
    <div ref="root" class="h-80 overflow-auto border rounded-md p-4" tabindex="0">
      <section v-for="section in sections" :id="section.id" :key="section.id" class="min-h-40">
        <h3 class="mt-0 font-semibold">{{ section.label }}</h3>
        <p class="text-sm text-muted-foreground">{{ section.text }}</p>
      </section>
    </div>
    <div class="flex flex-col items-start gap-1">
      <NuiButton
        v-for="section in sections"
        :key="section.id"
        variant="ghost"
        :tone="section.id === activeId ? 'primary' : 'neutral'"
        size="sm"
        @click="jump(section.id)"
      >
        {{ section.label }}
      </NuiButton>
    </div>
  </div>
</template>

<script setup lang="ts">
import { useTemplateRef } from 'vue';
import { NuiButton, useScrollSpy } from '@numior/kit';

const root = useTemplateRef<HTMLElement>('root');

const sections = [
  { id: 'spy-demo-plan', label: 'Plan', text: 'Gather requirements and draw mockups.' },
  { id: 'spy-demo-build', label: 'Build', text: 'Write components and tests.' },
  { id: 'spy-demo-ship', label: 'Ship', text: 'Verify the build and publish.' },
  { id: 'spy-demo-support', label: 'Support', text: 'Triage requests and fix.' },
];

const { activeId, activate } = useScrollSpy(
  sections.map((section) => section.id),
  { root },
);

const jump = (id: string): void => {
  activate(id);
  document.getElementById(id)?.scrollIntoView({ block: 'start' });
};
</script>
```

## Signature

```ts
import { useScrollSpy } from '@numior/kit';

useScrollSpy: (ids: MaybeRefOrGetter<readonly string[]>, options?: ScrollSpyOptions) => ScrollSpy
```

```ts
import type { ScrollSpyOptions } from '@numior/kit';

interface ScrollSpyOptions {
  readonly root?: MaybeRefOrGetter<HTMLElement | null | undefined>;
  readonly line?: MaybeRefOrGetter<number | undefined>;
}
```

## Behaviour

`activeId` is the id of the current heading. `activate(id)` makes a section current at once and
keeps it until scrolling ends. So after a click on a contents item the highlight does not jump to
a neighboring heading.

Call `measure()` when the page content changes. [Toc](/en/components/toc) is built on this
composable.
