Skip to main content
Bases de Svelte
Introduction
Réactivité
Props
Logique
Évènements
Liaisons
Classes et styles
Actions
Transitions
Svelte avancé
Réactivité avancée
Réutiliser du contenu
Mouvements
Liaisons avancées
Advanced transitions
Context API
Special elements
<script module>
Next steps
Basic SvelteKit
Introduction
Routing
Loading data
Headers and cookies
Shared modules
Forms
API routes
$app/state
Errors and redirects
Advanced SvelteKit
Hooks
Page options
Link options
Advanced routing
Advanced loading
Environment variables
Conclusion

The <svelte:document> element allows you to listen for events that fire on document. This is useful with events like selectionchange, which doesn’t fire on window.

Add the onselectionchange handler to the <svelte:document> tag:

App
<svelte:document {onselectionchange} />

Avoid mouseenter and mouseleave handlers on this element, as these events are not fired on document in all browsers. Use <svelte:body> instead.

Modifier cette page sur Github

1
2
3
4
5
6
7
8
9
10
11
12
13
<script>
	let selection = $state('');
 
	const onselectionchange = (e) => {
		selection = document.getSelection().toString();
	};
</script>
 
<svelte:document />
 
<h1>Select this text to fire events</h1>
<p>Selection: {selection}</p>