Sveltekit noJS dropdowns

Published

Table of Contents

Make your website work without JavaScript using SvelteKit

This might be a pretty niche topic, but I wanted to write about how to make websites work without JavaScript using the SvelteKit framework.

Dropdown menus:
If you've made your own dropdown menus with JavaScript, obviously they won't work with JavaScript disabled. There are a few ways around this. The solution I came up with (for SSR) is to have the page be SSR'd with links in place of the menu buttons, and then as soon as the page is hydrated, replace the links with the buttons.

This isn't a perfect solution, as there is a delay between the page loading and the page hydration, but it does work with and without JS.

For a search bar, I did it something like this:

{#if !browser}
	 <a href="/search">Search</a>
{:else}
	 <button on:click={() => { showSearch = true; }}>Search</button>
{/if}

Browser is an environment variable provided by SvelteKit that lets you know if the code is being run in the browser or on the server. As you can see, when the page is rendered server-side (and thus browser is false) it renders a link to the search page. When the page is hydrated, browser is true, so it renders the button. In this case the button sets showSearch to true, which opens a dropdown search bar.

Another catch? with this method is that in some cases, there may not be a page equivalent to the dropdown or whatever that you can link to in place of the menu
!Can't think of any!

In some cases, you may have to create a page to substitute for the dropdown menu or whatever it is.

#article #coding/svelte #coding/sveltekit #writing Articles #coding/js

More posts: