# Scroll Progress

Thin bar at the top of the page or a scrolling container that fills as the reader scrolls.

- Category: Animations
- Status: stable
- Registry: https://markas.jenderalcorp.com/r/scroll-progress.json
- CLI: `npx markasui@latest add scroll-progress`

## When to use

Showing reading progress for a long article, or progress through a long panel, log, or modal body.

- Use one page bar per page
- With target parent, place the component as the first child of the element that scrolls
- Blade needs Alpine.js

## Code

### Blade

Save at `resources/views/components/markas/scroll-progress.blade.php`. Dependencies: alpinejs.

```blade
@props([
    'target' => 'page',
    'color' => 'primary',
    'size' => 'sm',
])

@php
    $root = 'pointer-events-none z-50 w-full';
    $bar = 'h-full w-full origin-left';
    $targets = [
        'page' => 'fixed inset-x-0 top-0',
        'parent' => 'sticky top-0 left-0',
    ];
    $sizes = [
        'sm' => 'h-0.5',
        'md' => 'h-1',
        'lg' => 'h-1.5',
    ];
    $colors = [
        'primary' => 'bg-primary',
        'success' => 'bg-success',
        'warning' => 'bg-warning',
        'danger' => 'bg-danger',
    ];
@endphp

<div
    x-data="{
        frame: 0,
        source: null,
        events: null,
        {{-- Isi bar sesuai posisi gulir halaman atau elemen induk. Pembaruan digabung per frame. --}}
        update() {
            this.frame = 0;
            const max = this.source.scrollHeight - this.source.clientHeight;
            const progress = max > 0 ? Math.min(Math.max(this.source.scrollTop / max, 0), 1) : 0;
            this.$refs.fill.style.transform = `scaleX(${progress})`;
        },
        schedule() {
            if (! this.frame) this.frame = requestAnimationFrame(() => this.update());
        },
        init() {
            const scroller = @js($target) === 'parent' ? this.$el.parentElement : null;
            this.source = scroller ?? document.documentElement;
            this.events = scroller ?? window;
            this.schedule = this.schedule.bind(this);
            this.update();
            this.events.addEventListener('scroll', this.schedule, { passive: true });
            window.addEventListener('resize', this.schedule, { passive: true });
        },
        destroy() {
            cancelAnimationFrame(this.frame);
            this.events?.removeEventListener('scroll', this.schedule);
            window.removeEventListener('resize', this.schedule);
        },
    }"
    aria-hidden="true"
    {{ $attributes->class([$root, $targets[$target], $sizes[$size]]) }}
><div x-ref="fill" class="{{ $bar }} {{ $colors[$color] }}" style="transform: scaleX(0)"></div></div>
```

```blade
{{-- Reading progress for the whole page --}}
<x-markas.scroll-progress />

{{-- Inside a scrolling container --}}
<div role="region" aria-label="Release notes" tabindex="0" class="relative h-64 overflow-y-auto">
    <x-markas.scroll-progress target="parent" color="success" size="md" />
    ...
</div>
```

### React

Save at `src/components/markas/ScrollProgress.tsx`. No extra dependencies.

```tsx
"use client";

import { useEffect, useRef, type ComponentProps } from "react";

const root = "pointer-events-none z-50 w-full";
const bar = "h-full w-full origin-left";
const targets = {
  page: "fixed inset-x-0 top-0",
  parent: "sticky top-0 left-0",
};
const sizes = {
  sm: "h-0.5",
  md: "h-1",
  lg: "h-1.5",
};
const colors = {
  primary: "bg-primary",
  success: "bg-success",
  warning: "bg-warning",
  danger: "bg-danger",
};

const cx = (...c: (string | false | null | undefined)[]) =>
  c.filter(Boolean).join(" ");

/**
 * Isi bar sesuai posisi gulir halaman atau elemen induk. Pembaruan digabung per frame.
 * Mengembalikan fungsi pelepas.
 */
function trackScroll(
  element: HTMLElement,
  fill: HTMLElement,
  target: keyof typeof targets,
) {
  const scroller = target === "parent" ? element.parentElement : null;
  const source = scroller ?? document.documentElement;
  const events: EventTarget = scroller ?? window;
  let frame = 0;
  const update = () => {
    frame = 0;
    const max = source.scrollHeight - source.clientHeight;
    const progress =
      max > 0 ? Math.min(Math.max(source.scrollTop / max, 0), 1) : 0;
    fill.style.transform = `scaleX(${progress})`;
  };
  const schedule = () => {
    if (!frame) frame = requestAnimationFrame(update);
  };
  update();
  events.addEventListener("scroll", schedule, { passive: true });
  window.addEventListener("resize", schedule, { passive: true });
  return () => {
    cancelAnimationFrame(frame);
    events.removeEventListener("scroll", schedule);
    window.removeEventListener("resize", schedule);
  };
}

export type ScrollProgressProps = Omit<ComponentProps<"div">, "children"> & {
  target?: keyof typeof targets;
  color?: keyof typeof colors;
  size?: keyof typeof sizes;
};

export function ScrollProgress({
  target = "page",
  color = "primary",
  size = "sm",
  className,
  ...props
}: ScrollProgressProps) {
  const rootRef = useRef<HTMLDivElement>(null);
  const fillRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (!rootRef.current || !fillRef.current) return;
    return trackScroll(rootRef.current, fillRef.current, target);
  }, [target]);

  return (
    <div
      ref={rootRef}
      aria-hidden="true"
      {...props}
      className={cx(root, targets[target], sizes[size], className)}
    >
      <div
        ref={fillRef}
        className={cx(bar, colors[color])}
        style={{ transform: "scaleX(0)" }}
      />
    </div>
  );
}
```

```tsx
import { ScrollProgress } from "@/components/markas/ScrollProgress";

<ScrollProgress />

<div role="region" aria-label="Release notes" tabIndex={0} className="relative h-64 overflow-y-auto">
  <ScrollProgress target="parent" color="success" size="md" />
  ...
</div>
```

### Vue

Save at `src/components/markas/ScrollProgress.vue`. No extra dependencies.

```vue
<script setup lang="ts">
import { onBeforeUnmount, onMounted, useTemplateRef, watch } from "vue";

type Target = "page" | "parent";

const props = withDefaults(
  defineProps<{
    target?: Target;
    color?: "primary" | "success" | "warning" | "danger";
    size?: "sm" | "md" | "lg";
  }>(),
  { target: "page", color: "primary", size: "sm" },
);

const root = "pointer-events-none z-50 w-full";
const bar = "h-full w-full origin-left";
const targets = {
  page: "fixed inset-x-0 top-0",
  parent: "sticky top-0 left-0",
};
const sizes = {
  sm: "h-0.5",
  md: "h-1",
  lg: "h-1.5",
};
const colors = {
  primary: "bg-primary",
  success: "bg-success",
  warning: "bg-warning",
  danger: "bg-danger",
};

/**
 * Isi bar sesuai posisi gulir halaman atau elemen induk. Pembaruan digabung per frame.
 * Mengembalikan fungsi pelepas.
 */
function trackScroll(element: HTMLElement, fill: HTMLElement, target: Target) {
  const scroller = target === "parent" ? element.parentElement : null;
  const source = scroller ?? document.documentElement;
  const events: EventTarget = scroller ?? window;
  let frame = 0;
  const update = () => {
    frame = 0;
    const max = source.scrollHeight - source.clientHeight;
    const progress =
      max > 0 ? Math.min(Math.max(source.scrollTop / max, 0), 1) : 0;
    fill.style.transform = `scaleX(${progress})`;
  };
  const schedule = () => {
    if (!frame) frame = requestAnimationFrame(update);
  };
  update();
  events.addEventListener("scroll", schedule, { passive: true });
  window.addEventListener("resize", schedule, { passive: true });
  return () => {
    cancelAnimationFrame(frame);
    events.removeEventListener("scroll", schedule);
    window.removeEventListener("resize", schedule);
  };
}

const rootEl = useTemplateRef<HTMLDivElement>("rootRef");
const fillEl = useTemplateRef<HTMLDivElement>("fillRef");
let stop = () => {};

function start() {
  stop();
  stop = () => {};
  if (!rootEl.value || !fillEl.value) return;
  stop = trackScroll(rootEl.value, fillEl.value, props.target);
}

onMounted(start);
watch(() => props.target, start, { flush: "post" });
onBeforeUnmount(() => stop());
</script>

<template>
  <div
    ref="rootRef"
    aria-hidden="true"
    :class="[root, targets[props.target], sizes[props.size]]"
  >
    <div
      ref="fillRef"
      :class="[bar, colors[props.color]]"
      style="transform: scaleX(0)"
    ></div>
  </div>
</template>
```

```vue
<template>
  <ScrollProgress />

  <div
    role="region"
    aria-label="Release notes"
    tabindex="0"
    class="relative h-64 overflow-y-auto"
  >
    <ScrollProgress target="parent" color="success" size="md" />
    ...
  </div>
</template>
```

### Svelte

Save at `src/lib/components/markas/ScrollProgress.svelte`. No extra dependencies.

```svelte
<script lang="ts">
  import type { HTMLAttributes } from "svelte/elements";

  const root = "pointer-events-none z-50 w-full";
  const bar = "h-full w-full origin-left";
  const targets = {
    page: "fixed inset-x-0 top-0",
    parent: "sticky top-0 left-0",
  };
  const sizes = {
    sm: "h-0.5",
    md: "h-1",
    lg: "h-1.5",
  };
  const colors = {
    primary: "bg-primary",
    success: "bg-success",
    warning: "bg-warning",
    danger: "bg-danger",
  };

  /**
   * Fills the bar with the scroll position of the page or the parent element. Updates are batched
   * per frame. Returns a cleanup function.
   */
  function trackScroll(
    element: HTMLElement,
    fill: HTMLElement,
    target: keyof typeof targets,
  ) {
    const scroller = target === "parent" ? element.parentElement : null;
    const source = scroller ?? document.documentElement;
    const events: EventTarget = scroller ?? window;
    let frame = 0;
    const update = () => {
      frame = 0;
      const max = source.scrollHeight - source.clientHeight;
      const progress =
        max > 0 ? Math.min(Math.max(source.scrollTop / max, 0), 1) : 0;
      fill.style.transform = `scaleX(${progress})`;
    };
    const schedule = () => {
      if (!frame) frame = requestAnimationFrame(update);
    };
    update();
    events.addEventListener("scroll", schedule, { passive: true });
    window.addEventListener("resize", schedule, { passive: true });
    return () => {
      cancelAnimationFrame(frame);
      events.removeEventListener("scroll", schedule);
      window.removeEventListener("resize", schedule);
    };
  }

  type Props = Omit<HTMLAttributes<HTMLDivElement>, "children"> & {
    /** Follow the whole page, or the closest scrolling parent element. */
    target?: keyof typeof targets;
    color?: keyof typeof colors;
    size?: keyof typeof sizes;
  };

  let {
    target = "page",
    color = "primary",
    size = "sm",
    class: className,
    ...rest
  }: Props = $props();

  let element = $state<HTMLDivElement>();
  let fill = $state<HTMLDivElement>();

  $effect(() => {
    const source = target;
    if (!element || !fill) return;
    return trackScroll(element, fill, source);
  });
</script>

<div
  bind:this={element}
  aria-hidden="true"
  {...rest}
  class={[root, targets[target], sizes[size], className]}
>
  <div
    bind:this={fill}
    class={[bar, colors[color]]}
    style="transform: scaleX(0)"
  ></div>
</div>
```

```svelte
<script lang="ts">
  import ScrollProgress from "$lib/components/markas/ScrollProgress.svelte";
</script>

<ScrollProgress />

<div
  role="region"
  aria-label="Release notes"
  tabindex="0"
  class="relative h-64 overflow-y-auto"
>
  <ScrollProgress target="parent" color="success" size="md" />
  ...
</div>
```

### Astro

Save at `src/components/markas/ScrollProgress.astro`. No extra dependencies.

```astro
---
import type { HTMLAttributes } from "astro/types";

const root = "pointer-events-none z-50 w-full";
const bar = "h-full w-full origin-left";
const targets = {
  page: "fixed inset-x-0 top-0",
  parent: "sticky top-0 left-0",
};
const sizes = {
  sm: "h-0.5",
  md: "h-1",
  lg: "h-1.5",
};
const colors = {
  primary: "bg-primary",
  success: "bg-success",
  warning: "bg-warning",
  danger: "bg-danger",
};

type Props = Omit<HTMLAttributes<"div">, "children"> & {
  /** Follow the whole page, or the closest scrolling parent element. */
  target?: keyof typeof targets;
  color?: keyof typeof colors;
  size?: keyof typeof sizes;
};

const {
  target = "page",
  color = "primary",
  size = "sm",
  class: className,
  ...rest
} = Astro.props;
---

<markas-scroll-progress class="contents" data-target={target}
  ><div aria-hidden="true" {...rest} class:list={[root, targets[target], sizes[size], className]}><div class:list={[bar, colors[color]]} style="transform: scaleX(0)"></div></div></markas-scroll-progress
>

<script>
  // One element per bar: setup runs for markup added later and after view transitions.
  class MarkasScrollProgress extends HTMLElement {
    private cleanup = () => {};

    connectedCallback() {
      const fill = this.firstElementChild?.firstElementChild as HTMLElement | null;
      if (!fill) return;
      // This element is display: contents, so its parent is the parent of the bar.
      const scroller = this.dataset.target === "parent" ? this.parentElement : null;
      const source = scroller ?? document.documentElement;
      const events: EventTarget = scroller ?? window;
      let frame = 0;
      // Fill the bar with the scroll position. Updates are batched per frame.
      const update = () => {
        frame = 0;
        const max = source.scrollHeight - source.clientHeight;
        const progress = max > 0 ? Math.min(Math.max(source.scrollTop / max, 0), 1) : 0;
        fill.style.transform = `scaleX(${progress})`;
      };
      const schedule = () => {
        if (!frame) frame = requestAnimationFrame(update);
      };
      update();
      events.addEventListener("scroll", schedule, { passive: true });
      window.addEventListener("resize", schedule, { passive: true });
      this.cleanup = () => {
        cancelAnimationFrame(frame);
        events.removeEventListener("scroll", schedule);
        window.removeEventListener("resize", schedule);
      };
    }

    disconnectedCallback() {
      this.cleanup();
    }
  }

  if (!customElements.get("markas-scroll-progress"))
    customElements.define("markas-scroll-progress", MarkasScrollProgress);
</script>
```

```astro
---
import ScrollProgress from "@/components/markas/ScrollProgress.astro";
---

<ScrollProgress />

<div
  role="region"
  aria-label="Release notes"
  tabindex="0"
  class="relative h-64 overflow-y-auto"
>
  <ScrollProgress target="parent" color="success" size="md" />
  ...
</div>
```

### Angular

Save at `src/app/markas/scroll-progress.component.ts`. No extra dependencies.

```ts
import {
  afterRenderEffect,
  ChangeDetectionStrategy,
  Component,
  computed,
  ElementRef,
  inject,
  input,
  viewChild,
} from "@angular/core";

const root = "pointer-events-none z-50 w-full";
const bar = "h-full w-full origin-left";
const targets = {
  page: "fixed inset-x-0 top-0",
  parent: "sticky top-0 left-0",
};
const sizes = {
  sm: "h-0.5",
  md: "h-1",
  lg: "h-1.5",
};
const colors = {
  primary: "bg-primary",
  success: "bg-success",
  warning: "bg-warning",
  danger: "bg-danger",
};

export type ScrollProgressTarget = keyof typeof targets;
export type ScrollProgressColor = keyof typeof colors;
export type ScrollProgressSize = keyof typeof sizes;

/**
 * Fills the bar with the scroll position of the page or the parent element. Updates are batched
 * per frame. Returns a cleanup function.
 */
function trackScroll(
  element: HTMLElement,
  fill: HTMLElement,
  target: ScrollProgressTarget,
) {
  const scroller = target === "parent" ? element.parentElement : null;
  const source = scroller ?? document.documentElement;
  const events: EventTarget = scroller ?? window;
  let frame = 0;
  const update = () => {
    frame = 0;
    const max = source.scrollHeight - source.clientHeight;
    const progress =
      max > 0 ? Math.min(Math.max(source.scrollTop / max, 0), 1) : 0;
    fill.style.transform = `scaleX(${progress})`;
  };
  const schedule = () => {
    if (!frame) frame = requestAnimationFrame(update);
  };
  update();
  events.addEventListener("scroll", schedule, { passive: true });
  window.addEventListener("resize", schedule, { passive: true });
  return () => {
    cancelAnimationFrame(frame);
    events.removeEventListener("scroll", schedule);
    window.removeEventListener("resize", schedule);
  };
}

/** Attribute selector on the bar div, so target="parent" follows the element it sits in. */
@Component({
  selector: "div[markas-scroll-progress]",
  changeDetection: ChangeDetectionStrategy.OnPush,
  host: { "aria-hidden": "true", "[class]": "classes()" },
  template: `<div
    #fillEl
    [class]="fillClasses()"
    style="transform: scaleX(0)"
  ></div>`,
})
export class ScrollProgress {
  /** Follow the whole page, or the closest scrolling parent element. */
  readonly target = input<ScrollProgressTarget>("page");
  readonly color = input<ScrollProgressColor>("primary");
  readonly size = input<ScrollProgressSize>("sm");

  protected readonly classes = computed(
    () => `${root} ${targets[this.target()]} ${sizes[this.size()]}`,
  );
  protected readonly fillClasses = computed(
    () => `${bar} ${colors[this.color()]}`,
  );
  private readonly host = inject<ElementRef<HTMLElement>>(ElementRef);
  private readonly fill = viewChild.required<ElementRef<HTMLElement>>("fillEl");

  constructor() {
    afterRenderEffect((onCleanup) => {
      const target = this.target();
      onCleanup(
        trackScroll(this.host.nativeElement, this.fill().nativeElement, target),
      );
    });
  }
}
```

```ts
import { Component } from "@angular/core";
import { ScrollProgress } from "./markas/scroll-progress.component";

@Component({
  selector: "app-release-notes",
  imports: [ScrollProgress],
  template: `
    <div
      role="region"
      aria-label="Release notes"
      tabindex="0"
      class="relative h-64 overflow-y-auto"
    >
      <div
        markas-scroll-progress
        target="parent"
        color="success"
        size="md"
      ></div>
      ...
    </div>
  `,
})
export class ReleaseNotes {}
```

## Props

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `target` | `'page' \| 'parent'` | page | page fixes the bar to the top of the window and follows the page scroll. parent makes it sticky inside its parent element and follows that element's scroll. |
| `color` | `'primary' \| 'success' \| 'warning' \| 'danger'` | primary | Bar color. |
| `size` | `'sm' \| 'md' \| 'lg'` | sm | Bar thickness of 2, 4, or 6 pixels. |

## Accessibility

- The bar is decorative and aria-hidden; the scroll position is already available to assistive technology.
- A scrolling container used with target parent should be focusable (tabindex 0) and named, so keyboard users can scroll it.
- The bar follows the scroll position directly, without animation, so reduced motion needs no special handling.

## Notes

- `target="page"` is fixed to the top of the window. `target="parent"` is sticky inside its parent and must be its first child.
- Updates are batched with `requestAnimationFrame` and only run while scrolling. The Blade version needs Alpine.js.
- The bar is decorative (`aria-hidden`). Make the scrolling container focusable and named so keyboard users can scroll it.
