Browser Bindings

Back

Loading concept...

๐ŸชŸ 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&&#35;39;s inner width] C --&gt; C1[Window&&#35;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 frame
  • document = 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&lt;br&gt;resize, scroll, keys"] B --> B2["Bind dimensions&lt;br&gt;innerWidth, scrollY"] C --> C1["Document events&lt;br&gt;selection, visibility"] C --> C2["Bind activeElement"] D --> D1["Body events&lt;br&gt;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 window directly 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! โœจ

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.