Discover how a few simple directives can transform your web code from messy to magical!
Why Use directive syntax in Svelte? - Purpose & Use Cases
Imagine you want to show or hide parts of your webpage based on user actions, like clicking a button or typing in a box, and you try to do this by manually changing the HTML or CSS every time.
Manually updating the page elements is slow and confusing. You have to write lots of code to check states and update the page, which can easily cause mistakes and make your code messy.
Svelte's directive syntax lets you write simple, clear instructions right in your HTML to control behavior like showing, hiding, or reacting to events automatically, making your code cleaner and easier to understand.
const button = document.querySelector('button'); button.addEventListener('click', () => { const box = document.querySelector('#box'); if (box.style.display === 'none') { box.style.display = 'block'; } else { box.style.display = 'none'; } });
<script>
let show = false;
</script>
<button on:click={() => show = !show}>Toggle</button>
{#if show}
<div id="box">Content</div>
{/if}You can build interactive web pages that update instantly and cleanly without writing complex manual code.
Think of a shopping site where clicking a product shows more details instantly without reloading the page or writing complicated JavaScript.
Manual DOM updates are slow and error-prone.
Directive syntax lets you write clear, automatic UI behavior.
It makes your code simpler and your app more responsive.