Skip to content

Active Element

Reactive document.activeElement

๐ŸŽฌ Usage

<script>
    import { active_el } from '@sveu/browser'

    const el = active_el()
</script>

๐Ÿ‘ฉโ€๐Ÿ’ปAPI

โ†ฉ๏ธ Returns

A subscribable store that contains the current active element.

๐Ÿงช Playground

Source Code ๐Ÿ‘€

Source Code
import { browser, to_writable } from "@sveu/shared"

import { on } from "../event_listener"

/**
 * Reactive `document.activeElement`
 *
 * @returns A readable store with the current active element.
 */
export function active_el<T extends HTMLElement>() {
    const { set, subscribe } = to_writable<T | null>(
        browser ? (document?.activeElement as T) : null
    )

    function handler() {
        set((document?.activeElement as T) || null)
    }

    if (browser) {
        on(
            window,
            "blur",
            (event) => {
                if (event.relatedTarget !== null) return

                handler()
            },
            true
        )

        on(window, "focus", handler, true)
    }

    return { subscribe }
}

Last update: 2023-03-09