bigskysoftware / htmx

</> htmx - high power tools for HTML
https://htmx.org
Other
38.19k stars 1.3k forks source link

HTMX events firing multiple times on back button press. When using hx-boost. #1346

Closed moxplod closed 1 year ago

moxplod commented 1 year ago

I am coming from the pjax world and using htmx to replace all clicks in the application.

I am using a blanket hx-boost on the body

<body class="light-skin" hx-boost="true" hx-target="#main" hx-swap="innerHTML show:window:top">

It works great, all the clicks are working exactly as I want them to. Life is great. Except when you press the back button. Things start behaving very weirdly then.

I have console log events firing on htmx events.

       var $b = $('body');
        $b.on('htmx:beforeRequest', function () {
            console.log('beforeRequest');
            NProgress.start().set(0.3);
        });

        $b.on('htmx:afterRequest', function () {
            console.log('afterRequest');
            loadEnd();
        });

        $b.on('htmx:responseError', function () {
            console.log('responseError');
            loadEnd();
        });

Events are fired correctly before you press the back button. But after the back button, each click starts firing afterRequest and beforeRequest events 2 times each. If you keep navigating and press the back button 2nd time, they start firing 3 times on each click.

The request to the server is still made only once.

Any ideas what is going wrong here and how to fix it?

Things I have tried that did not work:


       $b.off('htmx:beforeRequest');
        $b.off('htmx:afterRequest');
        $b.off('htmx:responseError');
moxplod commented 1 year ago

I found the solution. Adding it here in case anyone else faces it in the future.

It was to use https://htmx.org/attributes/hx-history-elt/

hx-history-elt

on