Load div on page load and then every n seconds with htmx?
Asked Answered
U

2

5

With HTMX I know I can poll e.g. "/news" every 2 seconds like this:

<div hx-get="/news" hx-trigger="every 2s">div>

But it takes 2s before the is triggered the first time after page load. What I want to do is to trigger the call to "/news" as soon as the page is loaded and then poll every 2s.

I've tried things such as:

<div hx-get="/news" hx-trigger="on load or every 2s">div>

and

<div hx-get="/news" hx-trigger="on htmx:afterOnLoad or every 2s">div>

But none of this works. How can I do this with HTMX?

(I know this is generally a bad practice with HTMX since you could just include the data from the server in the response, but I'd like to know out of curiosity :))

Unaffected answered 3/12, 2021 at 15:25 Comment(0)
K
17

You can add multiple triggers separated by comma. So this should probably work:

<div hx-get="/news" hx-trigger="load, every 2s">div>
Kratz answered 3/12, 2021 at 15:43 Comment(0)
C
1

You can use

hx-trigger="load,change"
Clo answered 1/9, 2023 at 12:48 Comment(1)
Welcome to Stack Overflow! Please read How to Answer and edit your answer to contain an explanation as to why this code would actually solve the problem at hand. Always remember that you're not only solving the problem, but are also educating the OP and any future readers of this post.Treacy

© 2022 - 2024 — McMap. All rights reserved.