htmx icon indicating copy to clipboard operation
htmx copied to clipboard

Hx-Retarget and this

Open ThePrimeagen opened this issue 2 years ago • 6 comments

Hx-Retarget and this as target causes null error and prevents htmx from operating any more on the site

the docs claim that this

This example uses hx-target="this" to make a link that updates itself when clicked:


context

doing a little 422 swap and from the server i was going to target the originating form to show the error

form

<form hx-post="/thing" hx-swap="beforeend" hx-target="#things">
    ...

server

name := c.FormValue("name")
email := c.FormValue("email")

if contactExists(data.Contacts, email) {
    c.Response().Header().Set("HX-Retarget", "this")
    c.Response().Header().Set("HX-Reswap", "outerHTML")
    return c.Render(422, "test", data)
}

this will result in the target code executing, notice no special handling for this

if (hasHeader(xhr,/HX-Retarget:/i)) {
  responseInfo.target = getDocument().querySelector(xhr.getResponseHeader("HX-Retarget"));
}

ThePrimeagen avatar Nov 05 '23 20:11 ThePrimeagen

i cannot use the Request header's Hx-Target since that is the target in the form not the form itself

ThePrimeagen avatar Nov 05 '23 20:11 ThePrimeagen

also glad to submit a pr to fix this

ThePrimeagen avatar Nov 05 '23 20:11 ThePrimeagen

Indeed, the HX-Retarget header works differently than hx-target, as its doc says:

HX-Retarget a CSS selector that updates the target of the content update to a different element on the page

I don't know if this was forgotten at the time extended selectors were added in, I don't see any reason to oppose to add support for those extended selectors for this header, relatively to the element that triggered the request

Feel free to submit a PR for it!

Telroshan avatar Nov 05 '23 20:11 Telroshan

i'll try to get something up in a bit

ThePrimeagen avatar Nov 05 '23 20:11 ThePrimeagen

This is another consequence of the extended CSS selectors being a construct that exists in a lot of places, so it looks like "one thing", but isn't necessarily supported everywhere that CSS selectors are.

You probably don't have to do too much more than change the line you identified to use findAttributeTarget (although the "this" behavior is a little weird).

Also another reason to unify their documentation: #1601

alexpetros avatar Nov 05 '23 23:11 alexpetros

@alexpetros thanks for the direction! this is great. i will still take care of this, just preparing for my talk still :)

ThePrimeagen avatar Nov 11 '23 00:11 ThePrimeagen