Im using JS API of the HTMX library to add contents. for example:
htmx.ajax('GET', url, {
target: '#js-product-list',
swap: 'beforeend', // Adding new stuff to already existing content
})
.then(() => {
...
Now lets say I would like to also update filter component on the page. Is it possible using JS API (without hx-* attributes)?
I tried
htmx.ajax('GET', url, {
target: '#js-product-list',
swap: 'beforeend',
swapOptions: {
swapOOB: '#js-filter-wrapper'
}
})
.then(() => {
...
Markup details:
htmx.ajax('GET', url, {
target: '#js-product-list',
swap: 'beforeend',
swapOptions: {
swapOOB: '#js-filter-wrapper'
}
})
<div class="container position-relative" id="js-main-content">
<header>
<div class="d-flex justify-content-between mx-1 my-3" id="js-filter-wrapper">
Filter content
</div>
<div class="mt-3 ms-1" id="js-main-title-wrapper">
<h1>Heading</h1>
</div>
</header>
<main class="row" id="js-product-list">
Product list content
</main>
</div>
This is what will be returned in response:
<div id="js-filter-wrapper" hx-swap-oob="#js-filter-wrapper">
Updated filter that will replace current filter
</div>
<div>
New products that will be appended to current ones using beforeend selector
</div>
2
Answers
You can issue separate HTMX requests to update different components. This is often the simplest approach if the components you want to update are distinct and their updates do not depend on each other.
To swap the filter OOB way, You will need to update the components, you desire . I have provided an example.