How to Use Click Event Handler in Svelte

How to Use Click Event Handler in Svelte

05/22 By frontendshape

Welcome to frontendshape. Today we will see how to use on:click event handler in svelte. In svelte click event is similar to vuejs, react, in svelte you can use on: to create events handler. Before we start you need to setup svelte on your system.

How to install & setup Vite + Typescript in Svelte


Svelte Click Event Handler Example

1) Svelte simple click event. you can create script tag function then call button on:click={event}.

<script>
  function handleClick() {
    alert('hello svelte!')
  }
</script>
<button on:click={handleClick}>Click Me</button>
svelte js click event

svelte js click event

2) Svelte inline click events handler.

<button on:click={ e => { alert('hello svelte!') } }>
  Click Me
</button>


3) Svelte event modifier using once.

once: removes the handler after the first time it runs.

<script>

  function handleClick() {
    alert('hello svelte!')
  }
</script>

<button on:click|once={handleClick}>Click Me</button>


4) increase value using click event in svelte.

<script>
	let count = 0
	
	function increase() {
		count ++
	}
</script>

<button on:click={increase}>
	Click me!
</button>

<h1>{count}</h1> 

Enter Your Search Query