htmx
htmx copied to clipboard
Expose the about-to-be-swapped-in element in htmx:beforeSwap
I would like to be able to run some JavaScript initialization code on HTML that arrives from the server before it is swapped into the DOM. This would avoid visual flickering if this is only done during the htmx:onLoad event. See also discord discussion 1 and discord discussion 2
There is a codepen that shows the flickering issue at https://codepen.io/wimdeblauwe/pen/eYrwZgv
You can use the htmx:afterSwap event which happens before the the new content is 'settled'. Your js would in any case very likely need to access the html actually in the dom, in order to manipulate it.
Hello folks! I'm in a similar situation. I noticed OOB swap had an event that was passing the fragment to the listener and I went for this one. In my case, it's bootstrap-select that I want to setup before the swap. It works as expected with this:
document.body.addEventListener("htmx:oobBeforeSwap", function(evt) {
evt.detail.fragment.childNodes.forEach(function(childNode) {
$(childNode).find(".selectpicker").selectpicker();
});
});
Maybe a new event htmx:beforeInserNode or htmx:afterMakingFragment could make sense to avoid this workaround and give a proper way to update an Element before it's attached to the actual DOM.