Back to Blog
Making a schedule on the laptop
Development
8 min read

Drag and Drop Calendar in JavaScript: Move and Resize Events

By SimpleCalendarJS Team

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

To build a drag and drop calendar in JavaScript, use Pointer Events (pointerdown, pointermove, pointerup plus setPointerCapture) and snap the pointer offset to time slots. Or turn it on in a library: FullCalendar's or EventCalendar's `editable`, or SimpleCalendarJS's `enableDragDrop` and `enableResize`. Then save each drop to your server and reload if the save fails.

Users expect to reschedule a meeting by grabbing it and dropping it on another slot, or stretch it by dragging its bottom edge. A drag and drop calendar in JavaScript looks simple, but you have to handle touch input, snap to time slots, save to your server and undo the move when the save fails. This guide covers the browser APIs, a small from-scratch version, what calendar libraries offer, and a complete example you can paste and run.

What Drag and Drop Means in a Calendar

In a calendar, "drag and drop" covers two separate interactions:

  1. Move: the user drags an event to another day or time. Start and end both change, and the duration stays the same.
  2. Resize: the user drags the event's end edge. Only the end changes (some libraries also allow resizing from the start).

Both interactions need the same supporting pieces:

  • Snapping: in week and day views, times should land on a grid (15 or 30 minutes), not wherever the pointer happens to stop. In month view, moves snap to whole days.
  • Constraints: no drops outside working hours, no overlaps, no changes to locked events.
  • Persistence: the new times go to your backend, and the UI has to reflect what the server actually saved.
  • Revert: if the save fails or a rule is broken, the event goes back to where it was.
  • Touch support: on a phone, the same gesture has to work without scrolling the page instead.

If you're still choosing a scheduler in general, the JavaScript calendar scheduler guide covers the wider decision. This post focuses on the dragging.

Native Drag and Drop API vs Pointer Events

Browsers give you two ways to build dragging: the HTML Drag and Drop API (draggable="true", dragstart, dragover, drop) and Pointer Events (pointerdown, pointermove, pointerup).

The HTML Drag and Drop API is designed to move data between drop targets. MDN describes how it works: data goes into a DataTransfer store and can only be written in dragstart. An element only becomes a drop target if you cancel dragover with preventDefault(). The data can only be read in drop. The browser draws a translucent "ghost" of the dragged element. That works well for a kanban card. It works poorly for a calendar event that has to snap to a slot and show its new time while it moves.

Pointer Events give you one event model for mouse, pen and touch. setPointerCapture(pointerId) sends every later event for that pointer to your element, even if the pointer leaves it. The CSS property touch-action: none stops the browser from treating the gesture as a scroll or zoom and firing pointercancel.

HTML Drag and Drop APIPointer Events
Touch supportiOS Safari only from version 15 (Can I Use)Mouse, touch and pen in one model
Drag previewBrowser-drawn ghost imageYou move the real element
Snapping while draggingAwkward: the ghost doesn't snapSimple: compute the slot on every pointermove
ResizingNot a good fitNatural: drag a handle
Dragging files or data in from outside the pageYesNo
Best forDropping external items onto the calendarMoving and resizing events inside it

For moving and resizing events inside a calendar, use Pointer Events. Use the native API only if users drag items into the calendar from elsewhere, such as an "unscheduled tasks" sidebar.

A Drag and Drop Calendar in Plain JavaScript (From Scratch)

The example below is a one-day column with a single event. You can move the event (drag its body) or resize it (drag the bottom handle). It snaps to 15 minutes, and if the save fails it goes back to its original time. It uses the same approach as a full week grid: convert pixels to minutes, round to the snap step, and always calculate from the event's original times.

<!doctype html> <html> <head> <style> .day { position: relative; height: 1152px; /* 24 hours × 48px */ max-width: 320px; border-left: 1px solid #ddd; background: repeating-linear-gradient(#fff 0 47px, #eee 47px 48px); } .block { position: absolute; left: 4px; right: 4px; box-sizing: border-box; padding: 4px 6px; border-radius: 6px; background: #4f46e5; color: #fff; font: 13px system-ui, sans-serif; cursor: grab; user-select: none; touch-action: none; /* stop the browser from scrolling during the drag */ } .handle { position: absolute; left: 0; right: 0; bottom: 0; height: 8px; cursor: ns-resize; } </style> </head> <body> <div id="day" class="day"></div> <script> const HOUR_PX = 48; const PX_PER_MIN = HOUR_PX / 60; const SNAP = 15; // minutes // Times in minutes from midnight const event = { id: 1, title: 'Design review', start: 9 * 60, end: 10 * 60 + 30 }; const day = document.getElementById('day'); const block = document.createElement('div'); block.className = 'block'; block.innerHTML = '<span></span><div class="handle"></div>'; day.append(block); const pad = (n) => String(n).padStart(2, '0'); const fmt = (m) => `${pad(Math.floor(m / 60))}:${pad(m % 60)}`; const snap = (m) => Math.round(m / SNAP) * SNAP; function render() { block.style.top = event.start * PX_PER_MIN + 'px'; block.style.height = (event.end - event.start) * PX_PER_MIN + 'px'; block.firstChild.textContent = `${event.title} ${fmt(event.start)}–${fmt(event.end)}`; } let drag = null; block.addEventListener('pointerdown', (e) => { drag = { mode: e.target.classList.contains('handle') ? 'resize' : 'move', startY: e.clientY, orig: { start: event.start, end: event.end }, }; block.setPointerCapture(e.pointerId); }); block.addEventListener('pointermove', (e) => { if (!drag) return; const delta = snap((e.clientY - drag.startY) / PX_PER_MIN); const { start, end } = drag.orig; if (drag.mode === 'move') { const duration = end - start; event.start = Math.min(Math.max(start + delta, 0), 1440 - duration); event.end = event.start + duration; } else { event.end = Math.min(Math.max(end + delta, start + SNAP), 1440); } render(); }); async function finish(commit) { if (!drag) return; const { orig } = drag; drag = null; const changed = orig.start !== event.start || orig.end !== event.end; if (!commit || !changed) { Object.assign(event, orig); render(); return; } try { const res = await fetch(`/api/events/${event.id}`, { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ start: event.start, end: event.end }), }); if (!res.ok) throw new Error(`HTTP ${res.status}`); } catch (err) { console.error('Save failed, reverting', err); Object.assign(event, orig); // put it back render(); } } block.addEventListener('pointerup', () => finish(true)); block.addEventListener('pointercancel', () => finish(false)); render(); </script> </body> </html>

Opened as a local file, the fetch fails and the event goes back to its original time, which shows the revert path working. Point it at a real endpoint to see a successful save.

This is about 100 lines for one event in one column. A real calendar also needs: dragging across day columns (use document.elementFromPoint or column offsets to find the target day), auto-scroll near the edges, overlap layout for events side by side, all-day rows, month-view day cells, and keyboard alternatives. That gap is why most teams use a library. The weekly calendar guide covers building the week grid itself.

Need a calendar in your app?

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

Drag and Drop in JavaScript Calendar Libraries

Most event calendars include drag and drop but keep it off by default. Here's how three dependency-free options compare, based on their docs as of 2026:

LibraryTurn it onCallbacksBuilt-in rulesNotes
FullCalendareditable: true (with a build system, add the interaction plugin)eventDrop, eventResize, plus start/stop hookssnapDuration, eventOverlap, eventConstraint, eventAllowinfo.revert() undoes a change; droppable accepts external items; eventResourceEditable for resource views
EventCalendar (vkurko)editable: true with the Interaction plugineventDrop, eventResizeeventStartEditable, eventDurationEditableMIT; the README cites about 39 kB Brotli-compressed
SimpleCalendarJSenableDragDrop: true, enableResize: trueonEventDrop (for both moves and resizes)None: validate in the callback~14 KB gzipped JS; mouse and touch

FullCalendar has the most detailed control. Its docs list options for minimum drag distance, revert animation, auto-scroll while dragging, snapping and overlap rules. Its eventDrop callback receives the event after the drop, the oldEvent, a delta duration and a revert function, which the docs recommend for when a server request fails. If you need constraint options out of the box or drag-from-sidebar, it's the stronger choice.

Building a Drag and Drop Calendar With SimpleCalendarJS

SimpleCalendarJS has month, week and day views where events can be moved (enableDragDrop) and resized by their end (enableResize), with mouse or touch. After either action, onEventDrop(event, oldStart, oldEnd, newStart, newEnd) runs. Every event needs a unique id for dragging to work.

It has no revert function and no constraint options, so the pattern is:

  1. Load events from your API in fetchEvents(start, end).
  2. In onEventDrop, check your rules. If the drop breaks one, skip the save.
  3. Otherwise send the new times to the server.
  4. Call calendar.refresh() in every case. It clears the cache and calls fetchEvents again, so the calendar shows what the server has: the new times if the save worked, the original ones if it didn't.

This complete page uses the CDN build:

<!doctype html> <html> <head> <link rel="stylesheet" href="https://unpkg.com/simple-calendar-js/dist/simple-calendar-js.min.css"> </head> <body> <p id="status" role="status"></p> <div id="calendar" style="height: 650px"></div> <script src="https://unpkg.com/simple-calendar-js/dist/simple-calendar-js.min.js"></script> <script> const statusEl = document.getElementById('status'); const notify = (msg) => { statusEl.textContent = msg; }; // Rule: timed events stay on one weekday, between 08:00 and 18:00 function withinWorkingHours(event, start, end) { if (event.allDay) return true; const weekday = start.getDay(); const endsBySix = end.getHours() < 18 || (end.getHours() === 18 && end.getMinutes() === 0); return start.toDateString() === end.toDateString() && weekday !== 0 && weekday !== 6 && start.getHours() >= 8 && endsBySix; } const calendar = new SimpleCalendarJs('#calendar', { defaultView: 'week', enabledViews: ['month', 'week', 'day'], weekStartsOn: 1, use24Hour: true, enableDragDrop: true, enableResize: true, fetchEvents: async (start, end) => { const params = new URLSearchParams({ start: start.toISOString(), end: end.toISOString() }); const res = await fetch(`/api/events?${params}`); if (!res.ok) return []; return res.json(); // [{ id, title, start, end, allDay, color, locked }] }, onEventDrop: async (event, oldStart, oldEnd, newStart, newEnd) => { const start = new Date(newStart); const end = new Date(newEnd); const resized = new Date(oldStart).getTime() === start.getTime(); // Extra fields such as `locked` are passed back in callbacks if (event.locked) { notify(`"${event.title}" is locked and can't be changed.`); calendar.refresh(); return; } if (!withinWorkingHours(event, start, end)) { notify('Events must stay within working hours (Mon–Fri, 08:00–18:00).'); calendar.refresh(); return; } try { const res = await fetch(`/api/events/${event.id}`, { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ start: start.toISOString(), end: end.toISOString() }), }); if (!res.ok) throw new Error(`HTTP ${res.status}`); notify(`${resized ? 'Resized' : 'Moved'} "${event.title}".`); } catch (err) { notify(`Couldn't save "${event.title}". It was put back.`); } calendar.refresh(); // show the server's version either way }, }); </script> </body> </html>

The inline style="height: 650px" matters. SimpleCalendarJS only reads an inline height for its fixed-height layout. A height from a stylesheet or utility class counts as no height. The status line uses role="status", so screen readers announce the result of each drop.

To try it without a backend, swap fetchEvents for a fixed array (fetchEvents: async () => events), update that array in onEventDrop, and call refresh(). The REST API events guide covers the loading side in more depth, including query parameters and caching.

In React

The same setup works with the core class in a useEffect. Destroy the instance in the cleanup:

import { useEffect, useRef } from 'react'; import SimpleCalendarJs from 'simple-calendar-js'; import 'simple-calendar-js/dist/simple-calendar-js.min.css'; export default function DraggableCalendar({ fetchEvents, saveEvent }) { const containerRef = useRef(null); const calendarRef = useRef(null); useEffect(() => { const calendar = new SimpleCalendarJs(containerRef.current, { defaultView: 'week', enableDragDrop: true, enableResize: true, fetchEvents, onEventDrop: async (event, oldStart, oldEnd, newStart, newEnd) => { try { await saveEvent(event.id, new Date(newStart), new Date(newEnd)); } catch (err) { console.error('Save failed', err); } finally { calendar.refresh(); } }, }); calendarRef.current = calendar; // use calendarRef.current.goToToday(), etc. return () => calendar.destroy(); }, [fetchEvents, saveEvent]); return <div ref={containerRef} style={{ height: 650 }} />; }

Wrap fetchEvents and saveEvent in useCallback in the parent. Otherwise the calendar is rebuilt on every render.

SimpleCalendarJS is free for personal, educational and open source projects. Commercial use (client sites, SaaS, internal tools) needs a paid license; see pricing. You can try drag and drop in the sandbox before installing anything.

Need a calendar in your app?

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

Saving Dropped Events Without Losing Data

The dragging is the easy part. Most bugs show up when the change is saved.

  • Validate on the server. Client-side rules (working hours, overlaps, locked events) are only for user feedback. Run the same checks in your API and return an error status when they fail, so the reload puts the event back.
  • Treat the server as the source of truth. Reloading after every drop costs one request but rules out a whole class of "the UI says 10:00, the database says 09:00" bugs. Optimistic updates without a reload are faster, but you have to handle the revert yourself.
  • Send unambiguous timestamps. toISOString() sends UTC, so the server always gets the same time whatever the browser's timezone. SimpleCalendarJS shows dates in the browser's local time and has no timezone option. If events belong to a different timezone, convert them before returning them from fetchEvents.
  • Handle concurrent edits. If two people can edit the same calendar, send a version number or updated_at with the PATCH and reject outdated writes. The reload then shows the other person's change.
  • Recurring events need a policy. SimpleCalendarJS doesn't expand recurrence rules, so each occurrence you return is a separate event. Decide whether a drag moves one occurrence or the whole series, and include an occurrence identifier in the extra fields so onEventDrop knows which one.

For staffing use cases, the shift scheduling calendar tutorial applies these rules to rosters.

Click and Keyboard Alternatives to Dragging

Dragging shouldn't be the only way to reschedule. WCAG 2.2 Success Criterion 2.5.7, Dragging Movements (Level AA), requires that anything done by dragging can also be done "by a single pointer without dragging", unless dragging is essential. The W3C explanation points out that people using trackballs, head pointers or eye-gaze systems often find dragging difficult or error-prone.

For a calendar, the usual answer is an edit form:

  1. Use onEventClick(event, mouseEvent) to open your own dialog with start and end fields. SimpleCalendarJS doesn't include editing forms.
  2. On save, send the same PATCH request you use for drops, then call calendar.refresh().
  3. Optionally, use onSlotClick(date, mouseEvent) to open the same form for a new event at that time.

Because both paths call the same save function, the rules and revert logic live in one place. It also helps on small phones, where precise dragging on a 15-minute grid is hard anyway.

When Another Library Is the Better Choice

SimpleCalendarJS covers the common case: moving and resizing events in month, week and day views, with your own rules in a single callback. Choose something else when you need:

  • Drag between resources (rooms, staff, machines). SimpleCalendarJS has no resource or timeline views. FullCalendar's resource views with eventResourceEditable handle this.
  • Drag in from outside the calendar, such as an "unscheduled jobs" list. FullCalendar's droppable and eventReceive support it. SimpleCalendarJS only moves events that are already on the calendar.
  • Declarative constraints like eventConstraint, eventOverlap or a custom snapDuration, without writing the checks yourself.
  • Resizing from the start edge. FullCalendar has eventResizableFromStart. SimpleCalendarJS resizes from the end.
  • An MIT license for a commercial product without buying one. EventCalendar is MIT-licensed and supports dragging and resizing through its Interaction plugin.

If your app needs a lightweight month/week/day calendar where users drag meetings, bookings or shifts around and your server has the final say, the pattern above is all you need. The docs list every option.

Sources & Further Reading

Image Credits

Image free to use under the Pexels License.

Frequently Asked Questions

Does HTML5 drag and drop work on mobile browsers?

Partly. Can I Use lists native drag and drop on iOS Safari from version 15 only, and touch behaviour still differs between browsers. For calendar events, Pointer Events are more reliable: one code path handles mouse, touch and pen. Add touch-action: none to draggable elements so the browser doesn't cancel the gesture to scroll the page.

How do I snap dragged calendar events to 15-minute intervals?

Turn the pointer's vertical movement into minutes (pixels divided by pixels-per-minute), then round to the nearest step: Math.round(minutes / 15) * 15. Apply the rounded change to the event's original start and end, not to the last position. That way rounding errors don't pile up while the user drags.

How do I undo a calendar drag when the server save fails?

In FullCalendar, call info.revert() in the eventDrop or eventResize callback. In SimpleCalendarJS, send the change to your API in onEventDrop and call calendar.refresh() whether the save works or not. refresh() clears the cache and calls fetchEvents again, so the calendar shows whatever times the server actually has.

How can I tell a move from a resize in SimpleCalendarJS?

onEventDrop runs after both a drag and a resize, with (event, oldStart, oldEnd, newStart, newEnd). If the start time didn't change and only the end did, the user resized the event. If the start changed, the user moved it. Compare with getTime(), because two separate Date objects never equal each other with ===.

Can I stop events from overlapping when users drag them?

FullCalendar has eventOverlap and eventConstraint options for this. SimpleCalendarJS has no overlap option. Check the new range against your other events in onEventDrop, and if it overlaps, skip the save and call refresh() to put the event back. Run the same check on the server, since client-side checks can be bypassed.

Can I drag events between resources or staff rows in SimpleCalendarJS?

No. SimpleCalendarJS has month, week, day and list views but no resource or timeline views, so you can't drag an event from one person's row to another's. If you need that, look at FullCalendar's premium resource views (eventResourceEditable) or another scheduler built around resources.

Add a calendar to your app today

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

Keep Reading