HTMX experiments: triggers
I've been hearing a lot about HTMX so I decided to look into it. I also plan to create a new web app and felt that HTMX would be a great fit. However, I am wholly unfamiliar with the framework, so I decided to document my journey via these posts.
First experiment: use HTMX to communicate with a public API server that returns a text string. As per my research, the workflow runs like this:
Trigger HTMX to call the API server.
API server returns a response to HTMX.
HTMX parses the response received.
Note that my main goal here is to understand how to effectively use HTMX for client-server communication. I start my journey by reading the documentation found here:
Triggers
I learned that triggers are events or actions that will make HTMX send an API call. After a few attempts, I created the codepen below which provides quick examples of triggers supported by HTMX:
See the Pen HTMX triggers by r0d3r1ck0rd0n3z ( @r0d3r1ck0rd0n3z) on CodePen.
Click the HTML button above to inspect the backend code. For each section, note the following properties:
-
hx-trigger
Indicates which event will start the API call. If no trigger is defined, HTMX will use the click event. An event modifier can be added to specify additional refinements for the trigger. -
hx-get
Defines the URL of the API to call. For the examples above, it's for https://v2.jokeapi.dev which returns a one-line plain text response.
For an example that uses an API that returns JSON data, see the last example.
Comparison with vanilla JS
Compare the code above with the standard method for consuming JSON content using vanilla JS:
Also consider that the above code only extracts one item from the response. If multiple items are needed, additional code has to be manually written and tested.
Using HTMX, however, makes the code leaner and easier to understand since the logic behind parsing the response and adding it to the dom is already handled by the framework.
Moving forward
After this initial attempt, I do plan to play more with the hx-get="{event} {modifier}" attribute. Some ideas worth exploring:
- Use of other JS events to trigger the HTMX API call.
- Use of other HTMX event modifiers (changed, delay, throttle, etc).
- Use of hx-ext="client-side-templates" to format the received response.
- Use of multiple triggers that will start the API call.
Comments
Post a Comment