๐ช Svelte Browser Bindings: Your Appโs Superpowers!
The Magic Window Analogy ๐
Imagine your Svelte app lives in a cozy house. The house has:
- A Window (
svelte:window) โ You can see outside, know if itโs raining, and hear sounds - The Whole House (
svelte:document) โ The entire structure responds to what happens - The Body/Living Area (
svelte:body) โ Where all the action happens inside
These special Svelte elements let your app listen to and respond to whatโs happening in the browser โ just like you notice when someone knocks on your door!
๐ช <svelte:window> โ The Window Watcher
What Is It?
<svelte:window> is like having super ears that can hear everything happening in your browser window!
Simple Example:
- When you resize your browser? Window knows!
- When you scroll the page? Window knows!
- When you press a key? Window knows!
๐ฏ Listening to Events
<script>
function handleKeydown(event) {
alert(`You pressed: ${event.key}`);
}
</script>
<svelte:window on:keydown={handleKeydown} />
What happens? Press any key โ Your app says hello! ๐
๐ Common Window Events
| Event | When It Fires |
|---|---|
scroll |
User scrolls the page |
resize |
Window size changes |
keydown |
Key is pressed |
keyup |
Key is released |
online |
Internet connects |
offline |
Internet disconnects |
๐ Binding Window Properties
Hereโs the magic โ you can bind to window properties and they update automatically!
<script>
let innerWidth;
let innerHeight;
let scrollY;
</script>
<svelte:window
bind:innerWidth
bind:innerHeight
bind:scrollY
/>
<p>Window: {innerWidth} x {innerHeight}</p>
<p>Scrolled: {scrollY}px</p>
๐ Bindable Window Properties
graph TD A["svelte:window bindings"] --> B["innerWidth"] A --> C["innerHeight"] A --> D["outerWidth"] A --> E["outerHeight"] A --> F["scrollX"] A --> G["scrollY"] A --> H["online"] B --> B1["Window&#39;s inner width] C --> C1[Window&#39;s inner height"] F --> F1["Horizontal scroll position"] G --> G1["Vertical scroll position"] H --> H1["true if connected"]
๐ฎ Real-World Use Case: Scroll Progress
<script>
let scrollY;
let innerHeight;
$: progress = Math.min(
scrollY / innerHeight * 100,
100
);
</script>
<svelte:window
bind:scrollY
bind:innerHeight
/>
<div class="progress-bar">
{progress.toFixed(0)}% scrolled
</div>
๐ <svelte:document> โ The House Manager
What Is It?
<svelte:document> listens to the entire document โ like having sensors throughout your whole house!
Key Difference from Window:
window= The browser framedocument= The actual webpage content
๐ฏ Perfect For Selection Events
<script>
let selection = '';
function handleSelection() {
selection = document
.getSelection()
?.toString() ?? '';
}
</script>
<svelte:document
on:selectionchange={handleSelection}
/>
<p>Select some text below:</p>
<p>Hello world! Try selecting me.</p>
{#if selection}
<p>You selected: "{selection}"</p>
{/if}
๐ Common Document Events
| Event | When It Fires |
|---|---|
selectionchange |
Text selection changes |
visibilitychange |
Tab shown/hidden |
fullscreenchange |
Fullscreen toggled |
๐ Document Binding: activeElement
Track which element is focused:
<script>
let activeElement;
</script>
<svelte:document
bind:activeElement
/>
<input placeholder="Click me!" />
<button>Or me!</button>
<p>
Active: {activeElement?.tagName ?? 'none'}
</p>
๐ <svelte:body> โ The Living Room
What Is It?
<svelte:body> is for events on the <body> tag โ perfect for detecting when users interact anywhere on the visible page!
๐ฏ Perfect For: Mouse Enter/Leave
<script>
let isHovering = false;
</script>
<svelte:body
on:mouseenter={() => isHovering = true}
on:mouseleave={() => isHovering = false}
/>
<div class="app">
{isHovering
? '๐ Welcome!'
: '๐ Come back!'}
</div>
๐ฎ Drag and Drop Detection
<script>
let isDragging = false;
</script>
<svelte:body
on:dragenter={() => isDragging = true}
on:dragleave={() => isDragging = false}
on:drop={() => isDragging = false}
/>
<div class:highlight={isDragging}>
{isDragging
? 'Drop it here!'
: 'Drag a file over'}
</div>
๐ญ Quick Comparison
graph LR A["Browser Bindings"] --> B["svelte:window"] A --> C["svelte:document"] A --> D["svelte:body"] B --> B1["Window events<br>resize, scroll, keys"] B --> B2["Bind dimensions<br>innerWidth, scrollY"] C --> C1["Document events<br>selection, visibility"] C --> C2["Bind activeElement"] D --> D1["Body events<br>mouseenter, mouseleave"] D --> D2["Drag/drop detection"]
๐ช When to Use What?
| I want toโฆ | Use This |
|---|---|
| Know window size | svelte:window |
| Track scroll position | svelte:window |
| Detect keyboard input | svelte:window |
| Check online status | svelte:window |
| Track text selection | svelte:document |
| Know focused element | svelte:document |
| Detect tab visibility | svelte:document |
| Mouse enters/leaves page | svelte:body |
| Detect file drag over | svelte:body |
๐ก Pro Tips
โ Do This
- Use
bind:for reactive property access - Keep event handlers lightweight
- Clean up when component unmounts
โ Avoid This
- Donโt add too many listeners (performance!)
- Donโt use
windowdirectly when binding works
๐ Complete Example: Smart Header
<script>
let scrollY;
let innerWidth;
let online;
$: isMobile = innerWidth < 768;
$: headerHidden = scrollY > 100;
</script>
<svelte:window
bind:scrollY
bind:innerWidth
bind:online
/>
<header class:hidden={headerHidden}>
{#if !online}
<span>โ ๏ธ Offline</span>
{/if}
{#if isMobile}
<button>โฐ</button>
{:else}
<nav>Home | About | Contact</nav>
{/if}
</header>
๐ Summary
| Element | Superpower |
|---|---|
svelte:window |
See & react to window events + bind properties |
svelte:document |
Track document-level events + activeElement |
svelte:body |
Detect body interactions like mouse/drag |
Remember: These are your appโs superpowers for connecting with the browser. Use them wisely, and your app will respond to users like magic! โจ
