MatchMedia

Example

screenWidth >= 600px
HYDRATEEEEE
Resize the Browser

Example Source Code

Code

import { onMount } from "svelte";
import { writable } from "svelte/store";

export function createMatchMedia(query: string) {
	const mql = window.matchMedia(query);
	const value = writable(mql.matches);

	onMount(() => {
		const change = (event: MediaQueryListEvent) => {
			value.set(event.matches);
		};

		mql.addEventListener("change", change);

		return () => {
			mql.removeEventListener("change", change);
		};
	});

	return value;
}

Usage

<script lang="ts">
	import { createMatchMedia } from "@hooks/SvelteMatchMedia.svelte";

	const greaterThan600Px = createMatchMedia("(min-width: 600px)");
</script>

<div>
	<div>screenWidth &gt;= 600px</div>
	<div>
		{$greaterThan600Px}
	</div>
</div>