Getting Started
Core Concepts
Control
Interactivity
Performance
Pushing Data
HTMX Extensions
Miscellaneous
Configuration
Events Handler / Commands
In some cases, you need to update elements client side without having to do a network call.
For this you generally have to target an element with javascript and set an attribute, change the innerHTML, etc.
To make this work while still keeping a pure go feel, htmgo offers a few utility methods to execute various javascript on an element.
Example: When the form is submitted, set the button text to submitting and disable it, and vice versa after submit is done.
1func MyForm() *h.Element {
2 return h.Form(
3 h.Button(
4 h.Text("Submit"),
5 h.HxBeforeRequest(
6 js.SetDisabled(true),
7 js.SetText("Submitting..."),
8 ),
9 h.HxAfterRequest(
10 js.SetDisabled(false),
11 js.SetText("Submit"),
12 ),
13 ),
14 )
15}
The structure of this comes down to:
1. Add an event handler to the element
2. Add commands (found in the 'js' package) as children to that event handler
The current list of event handlers we have utility methods for so far are:
h.OnEvent
h.OnLoad
h.HxBeforeRequest
h.HxOnLoad
h.HxOnAfterSwap
h.OnClick
h.OnSubmit
h.HxBeforeSseMessage
h.HxAfterSseMessage
h.HxOnSseError
h.HxOnSseClose
h.HxOnSseConnecting
h.HxOnSseOpen
h.HxAfterRequest
h.HxOnMutationError
If there is not an existing method for the event you need, you can use the h.OnEvent method to add a handler for any DOM event or htmx event.
If there is not an existing method for the event you need, you can use the h.OnEvent method to add an event handler for any DOM or htmx event.
1h.Input(
2 h.OnEvent(
3 hx.BlurEvent,
4 js.SetValue("Input was blurred"),
5 )
6)
For more details on how they work, see the source for lifecycle. Any method that returns *Lifecycle can be used as an event handler, and any method that returns *Command can be used as a command.
The current list of commands supported can be found here.
Example: Evaluating arbitrary Javascript
1func MyButton() *h.Element {
2 return h.Button(
3 h.Text("Submit"),
4 h.OnClick(
5 // make sure you use 'self' instead of 'this' for referencing the current element
6 h.EvalJs(`
7 if(Math.random() > 0.5) {
8 self.innerHTML = "Success!";
9 }`
10 ),
11 ),
12 )
13}
More examples and usage can be found on the examples page, in the 'Interactivity' section.