HTMX - Extensions



HTMX extensions are used to manipulate the behavior of this library, you can define your extension in JavaScript and use that extension through hx-ext attribute.

How to use an Extension?

It is very easy to use an extension in HTMX, as there are two steps that you need to follow.

  • Step 1: You need to add an extension in your head element, which will add it to the htmx extension registry.
  • Step 2: Now you have to use the hx-ext attribute on your element to use it.

Example of HTMX Extension

Here in this example we will show you, how you can use a pre-defined extension through hx-ext attribute.

<script src="/tutorialspoint/htmx/debug.js" defer></script>

<div hx-ext="debug">
    <button hx-post="/content">Will Debug Code</button>
</div>

HTMX Ignoring Extension

If you have used the hx-ext attribute on any element then it will be applied to the DOM node along with all the child elements inside of that element. There is a way to ignore the extension htmx, suppose you do not want to apply your defined extension on some particular child element then you have to use ignore: keyword to stop it from being used.

<script src="/tutorialspoint/htmx/debug.js" defer></script>

<div hx-ext="debug">
    <button hx-post="/content">Will Debug Code</button>
    <button hx-post="/content" hx-ext="ignore:debug">Will Not Debug</button>
</div>

How to Define an Extension?

To define extension you need to use the htmx.defineExtension() function and the extension should be created on a separate file always. Do not try to define the extension in an inline <script> tag.

<script>
    (function(){
        htmx.defineExtension('my-ext', {
            onEvent : function(name, evt) {
                console.log("Fired event: " + name, evt);
            }
        })
    })()
</script>

Rules of Define an Extension

As you can see in the above code we have already defined an extension, with minimal effort and code. So when you are defining your extension there is something you need to maintain.

  • Extension Naming: Extensions should have names that are dash separated and that are reasonably short and understandable.
  • Override Default Extension: Extensions can override the default extension points to add or change functionality.

Extensions Override Default Extension Points

{
  init: function(api) { return null },
  getSelectors: function() { return null },
  onEvent: function(name, evt) { return true },
  transformResponse: function(text, xhr, elt) { return text },
  isInlineSwap: function(swapStyle) { return false },
  handleSwap: function(swapStyle, target, fragment, settleInfo) { return false },
  encodeParameters: function(xhr, parameters, elt) { return null }
}
Advertisements