Search code examples
htmx

Is it possible to intercept and change swapStyle in HTMX


I have a custom block of code I execute before swap which is working fine, but I now want to be able to change the swap style depending on some factors.

Here is the current code:

document.body.addEventListener('htmx:beforeSwap', function(evt) {
     if(evt.detail.xhr.status === 422){
        // allow 422 responses to swap as we are using this as a signal that
        // a form was submitted with bad data and want to rerender with the
        // errors displayed. Also, we want to swap the target element with the
        // element that has the id specified in the hx-target-422 attribute.
        // set isError to false to avoid error logging in console
        
        evt.detail.shouldSwap = true;
        evt.detail.isError = false;

        let target = document.querySelector(evt.detail.requestConfig.elt.getAttribute('hx-target-422'));

        evt.detail.target = target;
      }
  });

I have tried this: evt.detail.swapStyle = 'innerHTML'; but its not working.


Solution

  • This should work:

    document.body.addEventListener('htmx:beforeSwap', function(evt) {
        evt.detail.etc.swapOverride = 'innerHTML'
    });
    

    Be aware - this is not documented anywhere (so make sure you check for any side effects), possibly because the proper way is to override the HX-Reswap response header coming from the backend.