bigskysoftware / htmx

</> htmx - high power tools for HTML
https://htmx.org
Other
38.3k stars 1.31k forks source link

`htmx.config.requestClass` cannot contain a space i.e. cannot be multiple class names #2852

Open JackHerring opened 2 months ago

JackHerring commented 2 months ago

My use case is I want to add a spinner to the initiating button when an hx-post occurs

The CSS framework I am using does that with TWO extra classes on buttons - .spinner AND .spinner-(left|right)

When I set htmx.config.requestClass to e.g. 'spinner spinner-right' thus:

<meta name="htmx-config" content='{"requestClass":"spinner spinner-right"}'>

it explodes:

Uncaught DOMException: Failed to execute 'add' on 'DOMTokenList': The token provided ('spinner spinner-right') contains HTML space characters, which are not valid in tokens.
    at https://unpkg.com/htmx.org@2.0.2:1:29544
    at se (https://unpkg.com/htmx.org@2.0.2:1:5402)
    at Wt (https://unpkg.com/htmx.org@2.0.2:1:29460)
    at he (https://unpkg.com/htmx.org@2.0.2:1:43160)
    at https://unpkg.com/htmx.org@2.0.2:1:22304
    at HTMLButtonElement.i (https://unpkg.com/htmx.org@2.0.2:1:21340)

You cannot combine classes under an umbrella 'super' class in CSS

I can't see a hook to tackle this will a custom extension, either

So I am stuck. Is there a way to do this? All I can do is watch the class changing on the element and add and remove styles manually per the existence of .htmx-request

MichaelWest22 commented 2 months ago

I don't know if there is a way to make it process multiple classes

You can add custom event listeners via a little javascript

document.body.addEventListener('htmx:beforeRequest', function (evt) {
  // custom code to add css classes to indicators
  evt.target.classList.add('spinner', 'spinner-right')
});
document.body.addEventListener('htmx:afterRequest', function (evt) {
  // custom code to remove css classes from indicators
  evt.target.classList.remove('spinner', 'spinner-right')
});

These two events always happen at the same time as htmx adds and removes its its request class normally.