🌀 Alpine Portal v1.0.0

Alpine Portal

Screen-size-responsive, bidirectional DOM teleportation for Alpine.js v3.
Move elements between containers based on CSS media queries and restore them automatically.

📖 Introduction

Alpine's built-in x-teleport directive moves elements unconditionally to another part of the DOM. However, real-world responsive design often requires an element (such as a search bar, navigation links, or action button) to live in one container on mobile (e.g. inside a drawer) and inside a completely different layout container on desktop (e.g. the header bar).

Alpine Portal provides the x-portal directive to solve this natively:

ðŸ“Ķ Installation

Via CDN

Include Alpine Portal before loading Alpine.js:

HTML
<!-- Alpine Portal v1.0.0 -->
<script src="https://cdn.jsdelivr.net/gh/nabeghe/alpine-portal@v1.0.0/dist/alpine-portal.min.js" defer></script>

<!-- Alpine.js v3 -->
<script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>

Via NPM

Bash
npm install alpine-portal

Register the plugin with Alpine:

JavaScript
import Alpine from 'alpinejs';
import Portal from 'alpine-portal';

// Standard registration
Alpine.plugin(Portal);

// Or with custom screen breakpoints
Alpine.plugin(Portal, {
    screens: {
        tablet: 800,
        desktop: 1280,
    }
});

window.Alpine = Alpine;
Alpine.start();

⚡ Quick Start

Attach x-portal and a breakpoint condition to any element:

HTML
<!-- Source Container (Mobile) -->
<div id="mobile-drawer">
    <div x-portal="#desktop-header" x-portal:screen="768">
        <input type="search" placeholder="Search...">
    </div>
</div>

<!-- Target Container (Desktop) -->
<header id="desktop-header">
    <!-- Search input teleports here when viewport â‰Ĩ 768px -->
</header>

🔄 Core Mechanics

Exact Sibling Order Preservation

In earlier versions or naive implementations, returning an element uses appendChild(), which forces the element to the bottom of its original parent, permanently corrupting sibling layout order.

In Alpine Portal v1.0.0, an invisible DOM Anchor Comment node (<!-- x-portal-anchor -->) is placed immediately before the element upon initialization. When the element reverts, it returns precisely into its original sibling slot:

HTML
<div id="parent">
    <span>Item 1</span>
    <!-- Item 2 teleports to #target, but returns right between Item 1 and Item 3! -->
    <div x-portal="#target" x-portal:screen.md>Item 2</div>
    <span>Item 3</span>
</div>

Preventing Cumulative Layout Shift (CLS) with .spacer

When an element teleports away from its original container, the remaining content may abruptly collapse upward, triggering an unpleasant Cumulative Layout Shift (CLS).

Add the .spacer (or .placeholder) modifier. Alpine Portal leaves a matching placeholder element retaining the original element's computed width and height until it returns:

HTML
<!-- Leaves an invisible dimension-matched spacer in place -->
<div x-portal.spacer="#target" x-portal:screen="768">
    Fixed Height Hero Widget
</div>

📐 Breakpoint Syntax

The x-portal:screen directive supports numbers, named breakpoints, and ranges:

Syntax Generated Media Query Teleportation Behavior
x-portal:screen="640" (min-width: 640px) Teleports when viewport â‰Ĩ 640px
x-portal:screen="-640" (max-width: 640px) Teleports when viewport â‰Ī 640px
x-portal:screen.md (min-width: 768px) Tailwind named screen alias (modifier syntax)
x-portal:screen="'-md'" (max-width: 768px) Negative named screen alias
x-portal:screen="'640-1024'" (min-width: 640px) and (max-width: 1024px) Active strictly within range query
x-portal:screen="0" None Disables teleportation

Tailwind Preset Breakpoints

The following presets are built-in:

Arbitrary Media Queries (x-portal:media)

For custom conditions (orientation, aspect ratio, dark mode, pointer capabilities), use x-portal:media:

HTML
<!-- Teleport in landscape mode -->
<div x-portal="#sidebar" x-portal:media="(orientation: landscape)"></div>

<!-- Teleport on touch-screen devices -->
<div x-portal="#touch-menu" x-portal:media="(pointer: coarse)"></div>

ðŸ§Đ Placement Modifiers

Control where the element lands inside or relative to the destination selector:

Modifier DOM Action Description
.prepend target.prepend(el) Inserts as the first child of target
.append target.appendChild(el) Inserts as the last child of target (default)
.before target.before(el) Inserts immediately before target element
.after target.after(el) Inserts immediately after target element
HTML
<!-- Prepend to the top of the header -->
<div x-portal.prepend="#header-bar" x-portal:screen="768">Alert Banner</div>

ðŸŽŊ Multi-Target Responsive Routing

Often an element must travel between more than two containers. Pass a dictionary of { 'breakpoint': 'target' } routes:

HTML
<div x-portal="{
    '-640': '#mobile-drawer',
    '641-1024': '#tablet-toolbar',
    '1025': '#desktop-sidebar'
}">
    Multi-Target Navigation Links
</div>
How it works: The plugin sets up media query watchers for each route. The first matching route receives the element. If none match, it gracefully returns to its origin.

⚙ïļ State-Driven Teleportation (when)

Control teleportation reactively with Alpine data attributes using x-portal:when:

HTML
<div x-data="{ isModalOpen: false }">
    <button @click="isModalOpen = !isModalOpen">Toggle Search</button>

    <!-- Teleports to modal ONLY when isModalOpen is true AND viewport is mobile -->
    <div x-portal="#modal-body" x-portal:screen="-768" x-portal:when="isModalOpen">
        Search Bar
    </div>
</div>

ðŸ“Ą Lifecycle Events

Alpine Portal dispatches bubbling custom events on the portal element:

Event Trigger $event.detail Properties
portal:teleport Fired when element moves to target { target, targetElement, placement, portal }
portal:revert Fired when element returns to original position { originalParent, portal }
HTML
<div x-portal="#target" 
     x-portal:screen="640"
     @portal:teleport="console.log('Moved to: ', $event.detail.target)"
     @portal:revert="console.log('Returned back home!')">
    Interactive Element
</div>

⚡ Livewire & Teardown

Laravel Livewire: Alpine Portal automatically listens to livewire:navigating and unbinds all media query listeners before SPA navigation occurs.

Alpine v3 Cleanup: When an element is destroyed (e.g. by x-if or component teardown), Alpine Portal connects to Alpine's official cleanup() hook to automatically destroy listeners, remove anchors, and prevent memory leaks.

ðŸŽŪ Live Interactive Playground

Try testing responsive teleportation directly inside this documentation page:

Live Playground Box
Current Viewport:
SOURCE (Origin)
🚀 Live Teleporting Card â‰Ĩ 800px & when=true
TARGET CONTAINER

📋 Directive Cheat Sheet

Directive / Modifier Description
x-portal="#target"Teleports element to specified CSS selector
x-portal="{ '-640': '#m', '641': '#d' }"Multi-target routing map
x-portal.prependPrepends as first child inside destination
x-portal.appendAppends as last child inside destination (default)
x-portal.beforeInserts immediately before target element
x-portal.afterInserts immediately after target element
x-portal.spacerInserts invisible dimension spacer to eliminate CLS
x-portal:screen="640"Min-width breakpoint in pixels
x-portal:screen="-640"Max-width breakpoint in pixels
x-portal:screen.mdTailwind named breakpoint shortcut
x-portal:screen="'640-1024'"Range query breakpoint
x-portal:media="query"Arbitrary media query string
x-portal:when="condition"Alpine reactive condition
@portal:teleportFired on teleportation to target
@portal:revertFired on return to original parent