Svelte: add noscroll classname to body from component

Viewed 1948

I have a src/components/UI/Sidebar.svelte component with a variable toggle.

export let toggle = true;

I would like to add a classname of "noscroll" to the <body> when toggle is true to lock the body scroll. I have added this on the src/template.html

<style>
    .noscroll { position: fixed; overflow-y:scroll };
</style>

What would be the best way to implement a y-axis scroll lock like this when the sidebar is open?

1 Answers

In your Sidebar.svelte you add a reactive function that toggles the classname

export let toggle;
$: document.body.classList[toggle ? 'add' : 'remove']('noscroll');

updated

Thanks to Rich Harris to point out that toggle takes a second argument specs this can be simplified to

export let toggle;

$: if (process.browser) document.body.classList.toggle('noscroll', toggle);

edit When using SvelteKit which came into public beta since this question was asked, you can also use the browser variable provided.

export let toggle;
import { browser } from '$app/env'

$: if (browser) document.body.classList.toggle('noscroll', toggle);
Related