fix up append and add prepend

This commit is contained in:
carson 2020-04-24 22:33:54 -07:00
parent ba6392034c
commit 077d93633b
2 changed files with 25 additions and 8 deletions

View File

@ -21,6 +21,10 @@
<button hx-get="foo.html" hx-target="#bar2" hx-swap-style="append">Trigger 3</button><span id="bar2">Bar</span>
</div>
<div>
<button hx-get="foo.html" hx-target="#bar3" hx-swap-style="prepend">Trigger b</button><span id="bar3">Bar</span>
</div>
<div>
<button hx-get="foo.html" hx-swap-style="outerHTML">Trigger 4</button>
</div>

View File

@ -26,7 +26,7 @@ var HTMx = HTMx || (function()
}
}
function makeNode(resp) {
function makeFragment(resp) {
let range = document.createRange();
return range.createContextualFragment(resp);
}
@ -37,10 +37,20 @@ var HTMx = HTMx || (function()
if (swapStyle === "outerHTML") {
target.outerHTML = resp;
processElement(target);
} else if (swapStyle === "prepend") {
let fragment = makeFragment(resp);
for (let i = fragment.children.length - 1; i >= 0; i--) {
const child = fragment.children[i];
processElement(child);
target.insertBefore(child, target.firstChild);
}
} else if (swapStyle === "append") {
let newChild = makeNode(resp);
processElement(elt);
target.appendChild(newChild)
let fragment = makeFragment(resp);
for (let i = 0; i < fragment.children.length; i++) {
const child = fragment.children[i];
processElement(child);
target.appendChild(child);
}
} else {
target.innerHTML = resp;
for (let i = 0; i < target.children.length; i++) {
@ -60,10 +70,13 @@ var HTMx = HTMx || (function()
{
if (this.status >= 200 && this.status < 400)
{
// Success!
let resp = this.response;
swapResponse(elt, resp);
}
// don't process 'No Content' response
if (this.status != 204) {
// Success!
let resp = this.response;
swapResponse(elt, resp);
}
}
else
{
elt.innerHTML = "ERROR";