Svelte.js Event modifiers tutorial
In this tutorial, we are going to learn about event modifiers in svelte by using examples.
Event Modifiers
In svelte.js, we have event modifiers which helps us to modify the default behavior of dom events.
once modifier
The once
modifier helps us to trigger the event only one time.
example:
<script>
function handleClick(){
alert('You can see me once')
}
</script>
<button on:click|once={handlerClick}>Click me</button>
In the above code, we have added once
modifer to on:click
event so that we can only fire the click
event once.
preventDefault
The preventDefault
modifier helps us to solve the default loading behavior of the browser whenever we submit a form.
example:
<script>
function handleSubmit() {
console.log("success");
}
</script>
<form on:submit|preventDefault={handleSubmit}> <input type="text" placeholder="Name" />
<button>submit</button>
</form>
stopPropagation modifier
stopPropagation
modifier helps us to stop reaching the event to the next element.
example:
<style>
div {
padding: 1rem;
border: 1px solid;
}
</style>
<div on:click={() => console.log('Outer div')}>
<h1>Outer div</h1>
<div on:click|stopPropagation={() => console.log('inner div')}>
<h1>Inner div</h1>
</div>
</div>
In the above code, if we click on an Inner div
it only fires the event on it instead of propagating it to Outer div
capture Modifier
It helps us to fire the event in capture phase instead of the bubbling phase.