// modification of suggestion by chatgpt - see README.txt // Handle swap failures where response exists document.body.addEventListener('htmx:beforeSwap', function (evt) { if (evt.detail.failed) { // swap failure (could be bad target or invalid response) console.warn("Swap failed:", evt.detail); const xhr = evt.detail.xhr; if (xhr && xhr.responseText) { const fallback = document.getElementById('fallback') || document.body; fallback.insertAdjacentHTML( 'beforeend', "
[Recovered beforeSwap] " + xhr.responseText + "
" ); } // prevent htmx from throwing its own error evt.preventDefault(); } }); // Handle missing targets with a generic message document.body.addEventListener('htmx:targetError', function (evt) { const target = evt.detail.target; // the actual DOM node // console.warn(target); const initiator = evt.detail.elt; // the element that triggered request // console.warn(initiator); let targetName; if (target) { // this does not work - see below 'if !targetname' block // target exists but swap failed for another reason targetName = target.id ? `#${target.id}` : target.tagName; } else { // target truly missing → try to read from hx-target attribute targetName = initiator.getAttribute('hx-target') || '(unknown)'; } // added because above if/else fails due to no target.id or target.tagName if (!targetName) { targetName = initiator.getAttribute('hx-target') || '(unknown)'; } // console.warn(targetName); console.warn("Target error, no response body available here:", evt.detail); // you can still insert a generic message const message = document.getElementById('hx-error') || document.body; message.insertAdjacentHTML( 'beforeend', `
[ERROR] Could not swap into target: "${targetName}", check it exists in DOM
` ); evt.preventDefault(); });