Skip to content

htmx and Astro View Transitions

New Course Coming Soon:

Get Really Good at Git

When using both htmx and Astro View Transitions, I had an event that fired on page load, so I added a astro:after-swap event to handle doing the same thing I did after page load, but after a page transition:

<script>
  const triggerFetchLastUpdated = () => {
    const contentElement = document.getElementById('fetch-last-updated')
    if (contentElement) {
      htmx.trigger(contentElement, 'click', {})
    }
  }

  htmx.onLoad(triggerFetchLastUpdated)

  document.addEventListener('astro:after-swap', () => {
    triggerFetchLastUpdated()
  })
</script>

But, I hit a problem: I noticed my HTMX event didn’t fire after a transition.

Solution: make sure you call htmx.process() after a page swap.

During the astro:after-swap event:

<script>
  const triggerFetchLastUpdated = () => {
    const contentElement = document.getElementById('fetch-last-updated')
    if (contentElement) {
      htmx.trigger(contentElement, 'click', {})
    }
  }

  htmx.onLoad(triggerFetchLastUpdated)

  document.addEventListener('astro:after-swap', () => {
    htmx.process(document.body)
    triggerFetchLastUpdated()
  })
</script>

You could also just have one event astro:page-load and skip handling 2 different events (htmx.onLoad and astro:after-swap):

<script>
 document.addEventListener('astro:page-load', () => {
   const contentElement = document.getElementById('fetch-last-updated')
   if (contentElement) {
      htmx.process(document.body)
      htmx.trigger(contentElement, 'click', {})
    }
  })
</script>

…but that’s slower as fires at the end of page navigation. astro:after-swap instead fires immediately after the new page replaces the old page.

Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. A course that helps you feel less frustrated with Git. Launching May 21, 2024. Join the waiting list!
→ Read my Astro Tutorial on The Valley of Code
→ Read my HTMX Tutorial on The Valley of Code

Here is how can I help you: