Events

If you’re new to JavaScript frameworks you might be confused by the use of inline event handlers because so far everyone told you to avoid doing so in JavaScript. That’s for a good reason because of separation of concerns to have our markup, styles, and logic separate which makes it easy to change and maintain.

Using a modern JavaScript framework all our concerns are in one place using components and writing declarative code and the framework doing the heavy DOM lifting and under the hood performance optimization.

If you want to know about all the Svelte events you won’t find them in the Svelte documentation because it’s just JavaScript so you can look at the MDN documentation for event listing. Under the generic Element you can find the event listener dblclick when someone performs a double click or mousemove when the user moves the mouse.

This is an example of an event listener in JavaScript.

Example.htmlCopy

<style>
  html,
  body {
    width: 100%;
    height: 100%;
    margin: 0;
  }

  div {
    height: 100%;
  }
</style>

<div id="app"></div>

<script>
  let appElement = document.querySelector('#app')

  let mouse = { x: 0, y: 0 }

  function handleMouseMove(event) {
    mouse.x = event.clientX
    mouse.y = event.clientY
    updateUI()
  }

  function updateUI() {
    appElement.innerHTML = `
      The mouse position is ${mouse.x} x ${mouse.y}
    `
  }

  appElement.addEventListener('mousemove', handleMouseMove)
</script>

In Svelte you use the on: directive to listen to DOM events.

App.svelteCopy

<script>
	let mouse = { x: 0, y: 0 }

	function handleMouseMove(event) {
		mouse.x = event.clientX
		mouse.y = event.clientY
	}
</script>

<div on:mousemove={handleMouseMove}>
	The mouse position is {mouse.x} x {mouse.y}
</div>

<style>
	div {
		height: 100vh;
	}
</style>

Svelte sends the event alongside your function if you do on:mousemove={handleMouseMove} but if you do it inline you have to pass it yourself on:mousemove={(event) => handleMouseMove(event)}.

Svelte has special modifiers for DOM events such as preventDefault. You can find a complete list under element directives and you can chain special modifiers together.

App.svelteCopy

<script>
	function handleSubmit() {
		console.log('Submit')
	}
</script>

<form on:submit|preventDefault={handleSubmit}>
	<input type="text" />
	<button type="submit">Submit</button>
</form>

Using preventDefault which is short for event.preventDefault() prevents the default behavior such as the form submitting causing a page reload because we want to control it using JavaScript on the client.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *