emmanuelbakare
emmanuelbakare

Reputation: 21

HTMX multiple event on one element - each event executing different request

Summary, How do I attach a click and a dblclick on same element in HTMX and also have each of the event executing different request (views).

.I am new to HTMX using django and i have this list

   <li class="list-group-item"
        hx-get="{% url 'quality:list'  competence.pk  %}"
        hx-target="#quality-list"
        hx-trigger="click"
        >

it works fine using the click event. I however also want it to execute another view (quality:update) when a dblclick is fired on it. i.e. on same element (li) click should implement details function and dblclick should implement update function

Upvotes: 1

Views: 4127

Answers (2)

yalow
yalow

Reputation: 73

I know this is old but another approach is to use 2 separate elements. It may be hard in this example because you are using <li> but for other people who may run to this in other cases, using another element could help.

For Example:

<div hx-trigger="click" hx-get="/request_1" hx-target="target_1">
    <div hx-trigger="dblclick" hx-get="/request_2" hx-target="target_2"></div>
</div>

There is also a discussion here about this: https://github.com/bigskysoftware/htmx/issues/118

Upvotes: 1

Dauros
Dauros

Reputation: 10557

We can modify the request path in the htmx:configRequest HTMX-event depending on the triggering event's type. First, we need to list the triggering events in the hx-trigger attribute. However for the single click event, we also need to add some delay, otherwise the single click event will be also fired twice before the double click event. I set the delay here to 0.5 second, but you can fine tune it for your needs/target audience.

<li class="list-group-item"
    hx-get="{% url 'quality:list' competence.pk %}"
    hx-target="#quality-list"
    hx-trigger="click delay:0.5s, dblclick"
    >

We can alter the path in the evt.detail.path property and we can check the triggering event's type at evt.detail.triggeringEvent.type:

<script>
document.body.addEventListener('htmx:configRequest', function(evt) {
    evt.detail.path = (evt.detail.triggeringEvent.type === 'dblclick') ? 
      '{% url 'quality:update' competence.pk %}' : 
      '{% url 'quality:list' competence.pk %}'
});
</script>

This small snipped can be placed anywhere in a Django template file.

Upvotes: 4

Related Questions