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?
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}
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 ...
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>
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 />
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.