Trongate Website Homepage

Targeting Elements

The mx-target attribute in Trongate MX is a powerful feature that allows you to specify which element in the DOM should be updated with the server response. This enables fine-grained control over where and how content is dynamically inserted or replaced, enhancing the interactivity and responsiveness of your web application without writing JavaScript.

Usage

By setting the mx-target attribute on an element, you define the target for the server's response content. If the mx-target attribute is not specified, the default behavior is to update the triggering element itself.

Basic Example:

<button mx-get="api/data" mx-target="#result">Get Data</button>
<div id="result"></div>

In this example, the response from the server will be inserted into the <div> element with the id "result".

Advanced Targeting

The mx-target attribute supports several advanced targeting options to provide more flexibility:

Option Description Example Syntax
CSS Selector A valid CSS selector that selects a specific element. mx-target="#myDiv"
this Targets the element that triggered the request. mx-target="this"
closest <selector> Finds the closest ancestor matching the selector. mx-target="closest li"
find <selector> Finds the first descendant matching the selector. mx-target="find .target"
body Targets the <body> element. mx-target="body"
none Does not replace any content, but the request is still made. mx-target="none"
For even more advanced targeting and positioning, combine the mx-target attribute with the mx-swap attribute. Full documentation for mx-swap is offered on the next page.

Detailed Examples:

Targeting the Triggering Element (this):

<button mx-get="api/data" mx-target="this">Replace Me</button>

This will replace the button itself with the response content.

Finding the Closest Ancestor (closest <selector>):

<button mx-get="api/data" mx-target="closest div">Load Content</button>

This will load the content into the closest <div> ancestor of the button.

Finding the First Descendant (find <selector>):

<div mx-get="api/data" mx-target="find .target">
    <div class="target"></div>
</div>

This will load the content into the first descendant with the class target.

Targeting the Body Element (body):

<button mx-get="api/data" mx-target="body">Load Content</button>

This will load the content into the <body> element.

No Content Replacement (none):

<button mx-get="api/data" mx-target="none">No Replacement</button>

This will make the request without updating any part of the DOM.

Summary

The mx-target attribute in Trongate MX provides developers with precise control over the placement of dynamic content updates. By mastering the use of this attribute, you can create more dynamic, responsive, and user-friendly web applications, leveraging the power and simplicity of Trongate MX.