function Htmx::on

Same name and namespace in other branches
  1. 11.x core/lib/Drupal/Core/Htmx/Htmx.php \Drupal\Core\Htmx\Htmx::on()

Creates a `data-hx-on` attribute.

This attribute instructs HTMX to react to events with inline scripts on elements.

`data-hx-on` supports two forms:

Single event, action pair:

  • $event is the name of the JavaScript event.
  • $action is the JavaScript statement to execute when the event occurs. This can be a short instruction or call a function in a script that has been loaded by the page.

This form results in `data-hx-on:event="action"` in the HTML.

Extended event action pairs:

  • $event is an associative array with event names and optional modifiers as keys and JavaScript statements as values.
  • The $action parameter is ignored.

This form results in `data-hx-on="event1 modifier -> action1; event2 -> action2"` in the HTML.

Example:

(new Htmx())->on([
  'event1 modifier' => 'action1',
  'event2' => 'action2',
])
  ->applyTo($element);

HTMX provides a number of custom events which can be used in either form. The extended form also supports a dozen event modifiers. Developers should review the full documentation using the link below.

Parameters

string|array<string, string> $event: HTMX event names are lowercase, colon-separated, of the pattern: htmx:phase:action[:sub-action].

string $action: The JavaScript statement.

int $modifiers: The modifiers to apply to the attribute. Defaults to no modifiers.

Return value

static Returns this object to allow chaining methods.

See also

https://four.htmx.org/reference/attributes/hx-on/

File

core/lib/Drupal/Core/Htmx/Htmx.php, line 769

Class

Htmx
Presents the HTMX controls for developers to use with render arrays.

Namespace

Drupal\Core\Htmx

Code

public function on(string|array $event, string $action = '', int $modifiers = self::NO_MODIFIER) : static {
  // We either have an array of event strings with associated actions or
  // a single event string and a single action.
  if (is_array($event)) {
    $name = 'hx-on';
    $eventActionPairs = [];
    foreach ($event as $eventName => $value) {
      $eventActionPairs[] = $eventName . ' -> ' . $value;
    }
    $action = implode('; ', $eventActionPairs);
  }
  else {
    $event = str_starts_with($event, ':') ? $event : ':' . $event;
    $name = "hx-on{$event}";
  }
  $this->createStringAttribute($name, $action, $modifiers);
  return $this;
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.