hx-trigger (Triggering Requests)

Introduction

By default, AJAX requests are triggered by the natural event of an element:

  • input, textarea & select are triggered on the change event

  • form is triggered on the submit event

  • everything else is triggered by the click event

If you want different behavior you can use the hx-trigger attribute to specify which event will cause the request.

Here is a div that posts to /mouse_entered when a mouse enters it:

div hx-post="/mouse_entered" hx-trigger="mouseenter">
   [Here Mouse, Mouse!]
</div>

Trigger Modifiers

A trigger can also have a few additional modifiers that change its behavior. For example, if you want a request to only happen once, you can use the once modifier for the trigger:

<div hx-post="/mouse_entered" hx-trigger="mouseenter once">
  [Here Mouse, Mouse!]
</div>

Other modifiers you can use for triggers are:

  • changed - only issue a request if the value of the element has changed

  • delay:<time interval> - wait the given amount of time (e.g. 1s) before issuing the request. If the event triggers again, the countdown is reset.

  • throttle:<time interval> - wait the given amount of time (e.g. 1s) before issuing the request. Unlike delay if a new event occurs before the time limit is hit the event will be discarded, so the request will trigger at the end of the time period.

  • from:<CSS Selector> - listen for the event on a different element. This can be used for things like keyboard shortcuts.