An implementation of HTMX swap attributes as an AlpineJS plugin.
Create a new file and paste in the plugin source.
Register the plugin before calling Alpine.start().
import AlpineSwap from '/my-alpine-plugins/alpine-swap.js'
window.Alpine = Alpine
Alpine.plugin(AlpineSwap)
Alpine.start()
Example:
$swap({
select: '#outerHTML .source',
target: '#outerHTML .target',
swapMethod: 'outerHTML',
transition: true
})
Default Settings Object
{
endpoint: window.location.href,
select: null,
target: el,
swapMethod: 'innerHTML',
transition: false,
morph: false,
settleDelay: 20 //milliseconds
}
Default: The current URL.
The URL for the GET request.
Default: Request body.
A valid CSS selector to select the element that will be swapped into the current page.
Note: This selector can select 1 or more elements. Ex. Both ul li and ul#unique-id are okay.
Default: The element that called $swap.
A valid CSS selector or HTML element.
Default: 'innerHTML'
Method | Description |
---|---|
innerHTML |
The default, replace the inner html of the target element. |
outerHTML |
Replace the entire target element with the response. |
beforebegin |
TInsert the response before the target element. |
afterbegin |
Insert the response before the first child of the target element. |
beforeend |
Insert the response after the last child of the target element. |
afterend |
Insert the response after the target element. |
Default: false
Use the new View Transitions API when a swap occurs.
Default: false
Whether or not to use Alpine Morph when inserting elements. Alpine Morph must be loaded first.
Only works with swap method outerHTML
Default: 20
Delay after swapping before items are considered "settled". Order of operations are derived from HTMX. Learn more here.
Added to the trigger element immediately before fetch()
is called and removed once the response is received.
Upon getting a response the target element is marked with the htmx-swapping class
Applied to the target just before swapping and removed immediately after swapping. Mirrors HTMX order of operations.
Added to each individual element insertion after alpine-swap-settling
and removed after the settlingDelay
is finished.
This event is triggered before an AJAX request is issued.
elt
Trigger elementtarget
Target elementrequestConfig
Options to be passed tofetch()
endpoint
elt
Trigger elementselect
CSS selector used for querySelectorfragment
Response fragmenttarget
Target elementswapMethod
transition
morph
endpoint
elt
Trigger elementselect
CSS selector used for querySelectorfragment
Response fragmenttarget
Target elementswapMethod
transition
morph
error
elt
Trigger elementtarget
Target element