I want to have a simple with way to hide and show an element with a button on svelte, how can I do it? Also is it simpler to do it in vanilla JS?
3 Answers
this code worked for me, it is a modified version of an example provided by Svelte which can be found here
<script>
let visible = true;
function toggleVissible() {
visible = !visible
}
</script>
<button on:click={toggleVissible}>
Hide
</button>
{#if visible}
<p>
This text will hide.
</p>
{/if}

- 76
- 4
Svelte has the {#if}
directive for that, which can be tied to local state, which in turn can be changed via a button's on:click
.
Whether it is easier in vanilla JS depends on many things, including the overall complexity. In the long run, things tend to be easier with Svelte.
I would recommend doing the tutorial...

- 166,899
- 29
- 327
- 400
Vanilla
Here is one way to do it in vanilla JS.
You can directly place this inside an .astro
component:
<button>Toggle</button>
<p>Content</p>
<script>
document.querySelector('button').onclick = () => {
const el = document.querySelector('p')
el.style.display = el.style.display === 'none' ? 'block' : 'none'
}
</script>
Svelte
And here is one example doing it in svelte:
<script>
let toggle = true
</script>
<button on:click={() => (toggle = !toggle)}> Toggle </button>
{#if toggle}
<p>Content</p>
{/if}
Make sure to import it with a client:
directive to get the JS actually shipped to the client in astro:
---
import Svelte from "./svelte.svelte";
---
<Svelte client:load />
Which one to choose?
I would recommend going with svelte, since it's so more readable, and you also have a better scalability, when you plan to add more features in the future.

- 1,400
- 1
- 9
- 18