Element reference bindings let you get a direct link to a specific HTML element in your code. This helps you control or check that element easily.
0
0
Element reference bindings (bind:this) in Svelte
Introduction
You want to focus an input box automatically when the page loads.
You need to measure the size or position of an element on the screen.
You want to call a method on a DOM element, like playing a video or scrolling.
You want to add or remove event listeners directly on an element.
You want to change element properties that are not handled by Svelte's reactive system.
Syntax
Svelte
<element bind:this={variableName} />The variableName will hold the actual DOM element after the component renders.
You can use this variable inside your script to interact with the element.
Examples
This binds the
inputElement variable to the input box so you can access it in your script.Svelte
<input bind:this={inputElement} />The
btn variable will refer to this button element.Svelte
<button bind:this={btn}>Click me</button>You can control the video player directly using the
videoPlayer variable.Svelte
<video bind:this={videoPlayer} src="video.mp4" controls></video>
Sample Program
This example shows how to use bind:this to get a reference to an input box. When you click the button, the input box gets focused automatically.
Svelte
<script> let inputRef; function focusInput() { inputRef.focus(); } </script> <input bind:this={inputRef} placeholder="Click the button to focus me" /> <button on:click={focusInput}>Focus the input</button>
OutputSuccess
Important Notes
Remember that the variable bound with bind:this is undefined before the component renders.
Use this binding carefully to avoid manipulating the DOM in ways that conflict with Svelte's reactive updates.
Summary
bind:this lets you get a direct link to an HTML element in your Svelte component.
You can use it to focus elements, measure them, or call their methods.
It helps when you need control beyond normal data binding.