The latest version of Svelte includes a new functionality dubbed attachments that enhances a web application’s DOM with interactive and reactive features. Svelte Attachments replace Svelte Actions.
Just like with Svelte Actions, developers use attachments to provide code to run when a component or DOM element is mounted or unmounted. Typically, the provided code would provision a listener for an event of interest, and remove that listener when the attachment target is unmounted. Attachments can also be used in conjunction with third-party libraries that require a target DOM element. Attachment that depends on reactive values will rerun when those values change.
Follows an example using the ScrambleTextPlugin
from the GSAP animation library:
<script>
import { gsap } from 'gsap'
import { ScrambleTextPlugin } from 'gsap/ScrambleTextPlugin'
gsap.registerPlugin(ScrambleTextPlugin)
function scramble(text, options) {
return (element) => {
gsap.to(element, {
duration: 2,
scrambleText: text,
...options
})
}
}
let text = $state('Svelte')
</script>
<input type="text" bind:value={text} />
<div {@attach scramble(text)}></div>
When the DOM is mounted for the first time, the text Svelte will be scrambled. Additionally, any further change to the text
value will also cause the text to be scrambled. Developers can experiment with the example in the Svelte playground.
Thus Svelte Attachments extend Svelte Actions which did not provide similar reactivity to its parameters. Additionally, Svelte Attachment can be set up on Svelte components, while Svelte Actions can only be declared on DOM elements. The release provides a mechanism to create attachments from actions, thus allowing developers to reuse existing libraries of actions.
Attachments can be used to encapsulate behavior separately from markup (as done in other UI frameworks, e.g. hooks in React). Examples of behaviors that were already implemented as actions and can now benefit from attachment affordances include clipboard copying, clickboard pasting into an element, capturing a click outside an element, masking user input, animating an element, pointer drag-to-scroll behavior, provisioning of shortcut keys, make an element swipeable, download on click, and many more.
Developers are invited to read the full documentation article online for an exhaustive view of the feature, together with detailed examples and explanations. Developers may also review the corresponding pull request for details about the motivation behind the feature and comments from developers.