aboutsummaryrefslogtreecommitdiff
path: root/src/lib/BackgroundImage.svelte
blob: fd62170e6d261b64e949bcb8d0ca0f47120b60ab (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<script lang="ts">
	import { onDestroy } from 'svelte'
	import { browser } from '$app/env'

	export let url: string

	function updateUrl() {
		if (!browser) return

		for (const styleEl of document.getElementsByClassName('background-image-style'))
			styleEl.innerHTML = ''

		// add bodyStyle to the head
		const style = document.createElement('style')
		style.classList.add('background-image-style')
		style.innerHTML = `:root{--background:url(${url})}`
		document.head.appendChild(style)
	}

	$: [url, updateUrl()]

	// get rid of the body style when we leave the page
	// not doing this will sometimes cause the background to stay
	onDestroy(() => {
		if (browser) {
			for (const styleEl of document.getElementsByClassName('background-image-style'))
				styleEl.innerHTML = ''
		}
	})
</script>