Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Trigger hx-get from JS #339

Closed
BoPeng opened this issue Jan 24, 2021 · 5 comments
Closed

Trigger hx-get from JS #339

BoPeng opened this issue Jan 24, 2021 · 5 comments

Comments

@BoPeng
Copy link
Contributor

BoPeng commented Jan 24, 2021

I have a cart-count element that

<span id="cart-count" hx-get="/cart/count"
     hx-trigger="load delay:1s" hx-target="#cart-count" hx-swap="outerHTML">
</span>

will try to hx-get the number of items in cart when the page is loaded.

Now, I have an add-to-cart button that, after its own stuff (e.g. change itself to remove from cart), send

            response['HX-Trigger-After-Swap'] = "cart-updated"

to the frontend.

I have an event listener that works,

document.body.addEventListener("cart-updated",
    function (evt) {
        alert("cart updated")
    })

but how can I trigger hx-get of the #cart-count element in JS?

Actually, it would be very convenient if I can write $cart-count as

hx-trigger="load delay:1s, cart-updated"

so that no JS is needed.

Update: According to #187 , hx-trigger="cart-updated" would work if the cart stuff is in the parent chain of add-to-cart element, but unfortunately this is not the case for me so some manual way to trigger hx-get is still needed.

@1cg
Copy link
Contributor

1cg commented Jan 24, 2021

Would you mind asking this question on stack overflow and linking to it, so we can build up some answers over there?

That's where people tend to go for things like this, and I have a good answer for you. :)

@BoPeng
Copy link
Contributor Author

BoPeng commented Jan 24, 2021

Like this?

@1cg
Copy link
Contributor

1cg commented Jan 24, 2021

Perfect, I answered it there too, but here is what I said:

You can listen for the event on the body of the document in the latest version of htmx using the from: modifier like so:

<span hx-get="/cart/count"
      hx-trigger="load delay:1s, cart-updated from:body" 
      hx-swap="outerHTML">
</span>

Note also that you don't need to use an explicit target here since the default target is the element that the hx-get is defined on.

@BoPeng
Copy link
Contributor Author

BoPeng commented Jan 24, 2021

That is cool!

I was thinking along the line of

response['HX-Trigger-Targets'] = '#cart-count`

but this from:body solution is good enough.

@BoPeng
Copy link
Contributor Author

BoPeng commented Jan 25, 2021

Just to confirm that the solution works perfectly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants