Skip to main content
Bases de Svelte
Introduction
Réactivité
Props
Logique
Évènements
Liaisons
Classes et styles
Attachments
Transitions
Svelte avancé
Réactivité avancée
Réutiliser du contenu
Mouvements
Liaisons avancées
Transitions avancées
API de contexte
Éléments spéciaux
<script module>
Next steps
Bases de SvelteKit
Introduction
Routing
Chargement de données
En-têtes et cookies
Modules partagés
Formulaires
Routes d’API
$app/state
Erreurs et redirections
SvelteKit avancé
Hooks
Options de page
Options de lien
Routing avancé
Chargement avancé
Variables d’environnement
Conclusion

Often, you need an attachment to depend on some parameters or component state. In this scenario, you can use an attachment factory — a function that returns an attachment.

In this exercise, we want to add a tooltip to the <button> using the Tippy.js library. The attachment is already wired up with {@attach tooltip}, but if you hover over the button (or focus it with the keyboard) the tooltip contains no content.

First, we need to convert our simple attachment into a factory function that returns an attachment.

App
function tooltip(node) {
	return (node) => {
		const tooltip = tippy(node);
		return tooltip.destroy;
	};
}

Next, the factory needs to accept the options we want to pass to Tippy (in this case just content):

App
function tooltip(content) {
	return (node) => {
		const tooltip = tippy(node, { content });
		return tooltip.destroy;
	};
}

The tooltip(content) expression runs inside an effect, so the attachment is destroyed and recreated whenever content changes.

Finally, we need to call the attachment factory and pass the content argument in our {@attach} tag:

App
<button {@attach tooltip(content)}>
	Hover me
</button>

Modifier cette page sur Github

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<script>
	import tippy from 'tippy.js';
 
	let content = $state('Hello!');
 
	function tooltip(node) {
		const tooltip = tippy(node);
		return tooltip.destroy;
	}
</script>
 
<input bind:value={content} />
 
<button {@attach tooltip}>
	Survolez-moi
</button>
 
<style>
	:global {
		[data-tippy-root] {
			--bg: #666;
			background-color: var(--bg);
			color: white;
			border-radius: 0.2rem;
			padding: 0.2rem 0.6rem;
			filter: drop-shadow(1px 1px 3px rgb(0 0 0 / 0.1));
 
			* {
				transition: none;
			}
		}
 
		[data-tippy-root]::before {
			--size: 0.4rem;
			content: '';
			position: absolute;
			left: calc(50% - var(--size));
			top: calc(-2 * var(--size) + 1px);
			border: var(--size) solid transparent;
			border-bottom-color: var(--bg);
		}
	}
</style>