Back to Blog
Developer coding on a laptop setup indoors
Framework
8 min read

htmx Calendar: How to Add One to an htmx App (htmx 2 and 4)

By SimpleCalendarJS Team

SimpleCalendarJS~14 KB gzipped · Zero dependencies · Any framework
Short answer

To add a calendar to an htmx app, render an empty container in your server template, create the calendar in `htmx.onLoad`, destroy it in htmx's cleanup event and load events from a JSON endpoint. Event forms stay as htmx partials. An `HX-Trigger` response header tells the calendar to call `refresh()`.

htmx lets you build interactive pages by swapping server-rendered HTML. The trouble is that a calendar is the kind of widget htmx was never meant to draw, and a JavaScript calendar dropped into an htmx page tends to break on the first swap. This guide shows how to build an htmx calendar that survives swaps, boosted navigation and the back button. Event forms stay as htmx partials, and the server tells the calendar when to reload.

The examples use Flask and Jinja on the server, but the server side is just two routes and a template. The same pattern works in Django, Rails, Laravel, Go or anything else that renders HTML.

Why a JavaScript Calendar Needs Special Handling in htmx

A calendar component creates its DOM, listeners and internal state when you call its constructor. htmx doesn't know about any of that. Three things can go wrong:

  1. New content isn't initialized. Code that runs on DOMContentLoaded only sees the first page. If the calendar arrives in a swap or a boosted link (hx-boost), nothing creates it. The htmx docs recommend htmx.onLoad for this: it runs your callback for every element htmx loads into the DOM, including the body at startup.
  2. Removed content isn't cleaned up. When htmx replaces the area around a calendar, the old instance is never destroyed. Document-level listeners and tooltips can leak. htmx 2 fires htmx:beforeCleanupElement "before htmx disables an element or removes it from the DOM". That's your chance to call destroy().
  3. History snapshots store markup without behavior. htmx 2 saves a copy of the page in a history cache (10 entries by default) and swaps it back on back navigation. The copy includes the calendar's rendered HTML but not the JavaScript instance, so you get a calendar that looks right and doesn't respond. The htmx docs give the fix for a similar widget, Tom Select: destroy it in htmx:beforeHistorySave so the snapshot is clean.

htmx 4, released on August 28, 2026, renames these events and drops the localStorage history cache. The last code section covers that change.

Choosing an Approach for Your htmx Calendar

Before you add a library, decide whether you need one. htmx can render a basic month grid by itself.

ApproachHow it worksGood forWeak at
Server-rendered gridThe server renders a month table; prev/next buttons hx-get the adjacent monthRead-only month views, a few events per dayWeek/day time grids, overlaps, drag & drop, tooltips
JS calendar + JSON feedServer template renders an empty container; the component fetches events as JSONInteractive calendars, schedulers, booking UIsNeeds a small client-side lifecycle (shown below)
JS calendar + hx-preserveSame as above, but the container keeps its identity across swapsPages where the region around the calendar re-renders oftenNeeds a stable id in every response

A pure htmx month view really is this simple:

<section id="month"> <header> <button hx-get="/month/2026/11" hx-target="#month" hx-swap="outerHTML">Previous</button> <h2>December 2026</h2> <button hx-get="/month/2027/1" hx-target="#month" hx-swap="outerHTML">Next</button> </header> <!-- server-rendered 7-column table of days and event links --> </section>

Once you need hourly slots, overlapping events or dragging, laying them out on the server gets painful fast. The rest of this guide uses the second approach. htmx handles everything around the calendar, and a component handles the grid.

Need a calendar in your app?

SimpleCalendarJS: ~14 KB gzipped, zero dependencies, works in any framework. Free for personal use.

Step 1: The Server Side (Pages, JSON and Partials)

The calendar needs one JSON endpoint that takes a date range. Everything else stays hypermedia: the event form is an HTML partial, and the create and move endpoints answer with an HX-Trigger header instead of JSON.

from datetime import datetime, timedelta from flask import Flask, jsonify, render_template, request app = Flask(__name__) # Local wall-clock times in "YYYY-MM-DDTHH:MM", the format a datetime-local input sends. EVENTS = [ {"id": 1, "title": "Sprint planning", "start": "2026-12-07T09:00", "end": "2026-12-07T10:30", "color": "#4f46e5"}, {"id": 2, "title": "Design review", "start": "2026-12-09T14:00", "end": "2026-12-09T15:00", "color": "#0891b2"}, ] def changed(body=""): """Empty 200 response that tells the page the calendar data changed.""" return body, 200, {"HX-Trigger": "calendar-changed"} @app.get("/") def calendar_page(): return render_template("calendar.html") @app.get("/api/events") def list_events(): start, end = request.args["start"], request.args["end"] # Same fixed-width format on both sides, so string order is date order. return jsonify([e for e in EVENTS if e["start"] < end and e["end"] > start]) @app.get("/events/new") def new_event(): start = request.args.get("start") or datetime.now().strftime("%Y-%m-%dT%H:00") end = (datetime.fromisoformat(start) + timedelta(hours=1)).strftime("%Y-%m-%dT%H:%M") return render_template("_event_form.html", title="", start=start, end=end, error=None) @app.post("/events") def create_event(): title = request.form.get("title", "").strip() start, end = request.form.get("start", ""), request.form.get("end", "") if not title or not start or end <= start: return render_template("_event_form.html", title=title, start=start, end=end, error="Add a title and an end time after the start.") EVENTS.append({"id": max((e["id"] for e in EVENTS), default=0) + 1, "title": title, "start": start, "end": end}) return changed() # the empty body clears the form; the header reloads the calendar @app.post("/events/<int:event_id>/move") def move_event(event_id): event = next((e for e in EVENTS if e["id"] == event_id), None) start, end = request.form.get("start", ""), request.form.get("end", "") if event and start and end > start: event["start"], event["end"] = start, end # Always send the trigger: a rejected move snaps back when the calendar re-fetches. return changed()

A few deliberate choices:

  • Validation errors come back with a 200 status and the re-rendered form. By default, htmx 2 doesn't swap 4xx responses, so a 422 would leave the user with no feedback unless you change its response-handling config.
  • Times are local wall-clock strings. The calendar shows dates in the browser's local time, and date-time strings without a Z are parsed as local time. If you store UTC, convert before returning events.
  • The move endpoint always fires the trigger. The calendar re-fetches after every drag, so it always shows what the server actually saved.

The form partial is ordinary htmx:

<!-- templates/_event_form.html --> <form hx-post="/events" hx-target="#event-dialog" hx-swap="innerHTML"> {% if error %}<p role="alert">{{ error }}</p>{% endif %} <label>Title <input name="title" value="{{ title }}" required></label> <label>Start <input type="datetime-local" name="start" value="{{ start }}" required></label> <label>End <input type="datetime-local" name="end" value="{{ end }}" required></label> <button type="submit">Save</button> <button type="button" hx-on:click="this.closest('form').remove()">Cancel</button> </form>

For a deeper look at the JSON side, such as caching, error handling and filtering by date range, see How to Load Calendar Events From a REST API.

Step 2: The Page Template

The page loads htmx, the calendar's UMD build and one small script. No bundler is needed. The calendar container is an empty div marked with a data attribute, so the same script can find calendars in any swapped fragment.

<!-- templates/calendar.html --> <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Team calendar</title> <link rel="stylesheet" href="https://unpkg.com/simple-calendar-js/dist/simple-calendar-js.min.css"> <script src="https://unpkg.com/htmx.org@2/dist/htmx.min.js"></script> <script src="https://unpkg.com/simple-calendar-js/dist/simple-calendar-js.min.js"></script> <script src="/static/calendars.js" defer></script> </head> <body hx-boost="true"> <nav> <a href="/">Calendar</a> <a href="/settings">Settings</a> </nav> <main> <div data-calendar data-events-url="/api/events" style="height: 640px"></div> <div id="event-dialog"></div> </main> </body> </html>

The inline style="height: 640px" matters. With a fixed inline height, month view shows "+N more" when a day overflows. Without one, the calendar grows to fit every event. A height from a stylesheet or utility class is treated as no height.

The script is deferred, so it runs before DOMContentLoaded, which is when htmx processes the body. The htmx.onLoad callback is registered in time for the first page load.

Wiring the htmx Calendar: Init, Cleanup and History

This is the whole client-side integration. It keeps a Map from container element to calendar instance, so initializing twice is harmless and every instance can be destroyed exactly once.

// static/calendars.js (htmx 2.x) const calendars = new Map(); // container element -> SimpleCalendarJs instance function toLocalISO(date) { const pad = (n) => String(n).padStart(2, '0'); return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}` + `T${pad(date.getHours())}:${pad(date.getMinutes())}`; } function findCalendars(root) { const found = [...root.querySelectorAll('[data-calendar]')]; if (root.matches && root.matches('[data-calendar]')) found.unshift(root); return found; } function initCalendars(root) { for (const el of findCalendars(root)) { if (calendars.has(el)) continue; el.replaceChildren(); // drop stale markup restored from a history snapshot const url = el.dataset.eventsUrl; const calendar = new SimpleCalendarJs(el, { defaultView: 'week', enabledViews: ['month', 'week', 'day', 'list'], weekStartsOn: 1, use24Hour: true, enableDragDrop: true, enableResize: true, fetchEvents: async (start, end) => { const params = new URLSearchParams({ start: toLocalISO(start), end: toLocalISO(end) }); const res = await fetch(`${url}?${params}`, { headers: { Accept: 'application/json' } }); return res.ok ? res.json() : []; }, onSlotClick: (date) => { htmx.ajax('GET', `/events/new?start=${encodeURIComponent(toLocalISO(date))}`, { target: '#event-dialog', swap: 'innerHTML', }); }, onEventDrop: (event, oldStart, oldEnd, newStart, newEnd) => { htmx.ajax('POST', `/events/${event.id}/move`, { swap: 'none', values: { start: toLocalISO(newStart), end: toLocalISO(newEnd) }, }); }, }); calendars.set(el, calendar); } } function destroyCalendars(root) { for (const el of findCalendars(root)) { const calendar = calendars.get(el); if (!calendar) continue; calendar.destroy(); calendars.delete(el); } } // Create calendars in the first page and in every fragment htmx loads. htmx.onLoad(initCalendars); // Destroy them before htmx removes their part of the DOM. htmx.on('htmx:beforeCleanupElement', (evt) => destroyCalendars(evt.detail.elt)); // Keep live calendars out of htmx 2's history snapshot. htmx.on('htmx:beforeHistorySave', (evt) => destroyCalendars(evt.detail.historyElt)); // A partial swap that pushed a URL may have kept a calendar on screen: bring it back. htmx.on('htmx:afterSettle', () => initCalendars(document.body)); // The server sends `HX-Trigger: calendar-changed` after any write. document.body.addEventListener('calendar-changed', () => { for (const calendar of calendars.values()) calendar.refresh(); });

What each hook does

  • htmx.onLoad calls initCalendars with each newly loaded element. That covers the first page, boosted navigation and any fragment that happens to contain a [data-calendar] container.
  • htmx:beforeCleanupElement passes the element being removed. destroyCalendars checks the element and its descendants, so it works whether htmx fires the event once for the swap target or once for each removed element.
  • htmx:beforeHistorySave follows the Tom Select recipe from the htmx docs. The snapshot stores an empty container, and when the page is restored, htmx.onLoad creates a fresh instance. The replaceChildren() call in initCalendars covers the case where old markup ends up in a snapshot anyway.
  • htmx:afterSettle fixes the one awkward case of the snapshot fix. If a partial swap pushes a URL but leaves the calendar on the page, the snapshot handler has just destroyed it. Calling initCalendars is idempotent, so running it after every settle costs a single querySelectorAll.

How the server talks back

The HX-Trigger response header fires a DOM event on the element that made the request, and the event bubbles up to the body. Both the form post and the htmx.ajax move call end with calendar-changed. A single listener on document.body calls refresh(), which clears the calendar's cache and calls fetchEvents again.

document.body itself is never replaced by hx-boost (it swaps the body's contents), so the listener survives navigation. If you want to pass data, send JSON instead: HX-Trigger: {"calendar-changed": {"id": 42}} puts the object's properties on evt.detail.

Editing works the same way. Add an onEventClick that calls htmx.ajax('GET', '/events/' + event.id + '/edit', …) into #event-dialog, and have the update endpoint return changed(). For more on drag and resize behavior, see Drag and Drop Calendar in JavaScript.

Keeping the Calendar Alive With hx-preserve

Destroying and recreating the calendar resets its view and date. Usually that's fine on navigation, but it's annoying when a filter form or sidebar re-renders a region that also contains the calendar. For that case, htmx's hx-preserve keeps an element as-is during a swap:

<div id="team-calendar" hx-preserve data-calendar data-events-url="/api/events" style="height: 640px"></div>

The rules from the htmx docs:

  • The element must have a stable id, and the response must contain an element with the same id. Its type and other attributes are ignored.
  • hx-preserve is not inherited.
  • Don't use hx-swap="none" on requests whose response might contain the preserved element, because it can be lost.
  • Preserved elements also keep their state through history navigation.

When filters change, the preserved calendar won't pick them up by itself. Have the filter endpoint send HX-Trigger: calendar-changed, and have fetchEvents read the current filter values (for example, new FormData(document.querySelector('#filters'))) when building its query string.

Test your cleanup handler with preserved elements in the htmx version you ship. If the calendar is destroyed during a preserving swap, skip [hx-preserve] containers in destroyCalendars and destroy them only on full navigation.

htmx 4: The Same Pattern With New Event Names

htmx 4.0.0 was released on August 28, 2026. As of December 2026, the htmx team keeps 2.x on the npm latest tag and 4.x on next until early 2027, so you install it explicitly (npm install htmx.org@4). They also say 2.x will be supported indefinitely. From your code's point of view, the changes that matter for a calendar are:

Jobhtmx 2htmx 4
Initialize new contenthtmx.onLoad (htmx:load)htmx.onLoad (now listens on htmx:after:process)
Before an element is removedhtmx:beforeCleanupElementhtmx:before:cleanup
Before a history snapshothtmx:beforeHistorySavehtmx:before:history:update
After the DOM settleshtmx:afterSettlehtmx:after:settle
History cachelocalStorage snapshotsNo cache by default; back navigation re-fetches the page (optional hx-history-cache extension uses sessionStorage)
HX-Trigger response headerSupportedUnchanged; HX-Trigger-After-Swap and HX-Trigger-After-Settle are removed

Since htmx 4 re-fetches pages on back navigation instead of restoring snapshots, the history handler isn't needed unless you add the history-cache extension. Replace the four htmx.on lines with:

// static/calendars.js (htmx 4.x): same helpers as above htmx.onLoad(initCalendars); // The cleanup event is dispatched on the element being cleaned up. htmx.on('htmx:before:cleanup', (evt) => destroyCalendars(evt.target)); htmx.on('htmx:after:settle', () => initCalendars(document.body)); document.body.addEventListener('calendar-changed', () => { for (const calendar of calendars.values()) calendar.refresh(); });

Two more htmx 4 changes affect the template:

  • Attribute inheritance is opt-in with a :inherited suffix, such as hx-confirm:inherited. Attributes you put on body and expect children to pick up need checking.
  • The team provides an upgrade checker that flags old event names and missing :inherited suffixes: npx htmx.org@4.0.0 upgrade-check -- ./templates.

If you're coming from a server framework with its own conventions, the Django and Laravel guides show the same JSON-plus-template split: Django template calendar and Laravel calendar.

Where SimpleCalendarJS Fits (and Where It Doesn't)

SimpleCalendarJS suits the htmx approach well. It ships a UMD build you load with a script tag, has zero dependencies, and weighs about 14 KB gzipped (about 19 KB with the CSS), so it doesn't add a build step to a server-rendered app. Its event model matches what htmx expects of a widget:

  • A single fetchEvents(start, end) function loads the visible range, and refresh() reloads it. Wiring it to HX-Trigger takes one listener.
  • destroy() gives the cleanup hook something to call.
  • onSlotClick, onEventClick and onEventDrop hand interactions back to you, so creating and editing events stays in server-rendered htmx forms instead of a built-in editor.
  • It has month, week, day and list views, plus date-picker and range-picker modes for booking forms. Dark mode is a uc-dark class, and theming uses CSS custom properties.

Be clear about what it doesn't do:

  • No recurring events. Expand recurrences on the server before returning them from /api/events.
  • No timezone option. Dates are shown in the browser's local time.
  • No resource or timeline views and no TypeScript types. If you need rooms or people as rows, look at the options in Best JavaScript Scheduler Libraries in 2026.

On licensing: SimpleCalendarJS is free for personal, educational and open source projects. Commercial use, including client sites, SaaS and internal company tools, requires a paid license. See pricing. You can try the options in the sandbox and read the full API in the docs.

Frequently Asked Questions

Can htmx render a calendar without any JavaScript library?

Yes. For a read-only month grid, the server can render the whole table, and buttons with hx-get can swap in the previous or next month. That works well for a few events per day. Week and day time grids, overlapping events, drag and drop and tooltips are where a client-side calendar component saves you a lot of work.

Why does my JavaScript calendar disappear or freeze after pressing the back button in htmx?

htmx 2 saves a snapshot of the page's HTML in its history cache and swaps it back in on back navigation. The snapshot holds the calendar's rendered markup but not its JavaScript instance, so the calendar looks right and does nothing. Destroy calendars in htmx:beforeHistorySave and recreate them when content loads.

How do I send a CSRF token with htmx.ajax requests from calendar callbacks?

htmx.ajax requests go through htmx's normal request pipeline, so you can add the header in a config-request listener. In htmx 2 that's htmx:configRequest, where you set evt.detail.headers['X-CSRF-Token'] to your token. htmx 4 renamed the event to htmx:config:request. Check its reference page for the detail shape before you port the code.

Does the calendar's month or week navigation update the URL in an htmx app?

No. SimpleCalendarJS doesn't touch the URL. If you want the visible date in the address bar, use the onNavigate callback to write a ?date= parameter with history.replaceState. When the page loads, read that parameter and pass it to the calendar as defaultDate.

Should calendar events come back as HTML or JSON in an htmx app?

Use JSON for the calendar's event feed. The component lays out events itself, so it needs data, not markup. Keep htmx and server-rendered HTML for everything around the calendar: create and edit forms, filters, sidebars and confirmation messages. That way the hypermedia approach covers most of the page.

Which timezone should the server use for calendar events?

SimpleCalendarJS shows dates in the browser's local time and has no timezone option. Either store and return local wall-clock times, as in this tutorial, or store UTC and convert to the user's timezone before returning events from fetchEvents. Pick one rule and apply it everywhere you read or write events.

Add a calendar to your app today

Free for personal projects. $49/year or $199 lifetime per commercial project.

Keep Reading