Back to Blog
A planner beside a laptop in a workspace
Tutorial
7 min read

Week View Calendar in JavaScript: Overlaps, All-Day and Now Line

By SimpleCalendarJS Team

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

A week view calendar in JavaScript is a 7-column time grid. Each event's top offset and height come from its minutes since local midnight. The hard parts are packing overlapping events into columns, splitting overnight events at midnight, moving all-day events to a top row and drawing a live now line. You can build these yourself (code below) or use a library that already does it.

Drawing seven columns with hour lines is the easy part of a week view calendar in JavaScript. It starts to go wrong when two meetings overlap, a deploy runs past midnight, a conference covers three days, or the clocks change for daylight saving. This guide works through each of those problems with plain, dependency-free code, then shows how to get the same view from a component.

If you need the basic grid first (finding the start of the week, the CSS Grid frame, navigation), start with How to Build a JavaScript Weekly Calendar. This post picks up the harder parts that guide leaves out.

What a Week View Calendar in JavaScript Has to Get Right

A week view is a time grid: a narrow gutter of hour labels, then one column per day, each column representing 24 hours from top to bottom. A timed event is a box whose top offset is its start time and whose height is its duration. On top of that basic mapping you need to handle the following:

ProblemWhat goes wrong if you ignore itTechnique
Minute-to-pixel mappingEvents drift an hour on DST daysUse wall-clock minutes (getHours()), not timestamp differences
Overlapping eventsBoxes cover each otherGroup overlaps into clusters, assign columns, share the width
Events crossing midnightBox overflows the column or vanishesSplit into one segment per day
All-day and multi-day eventsA 24-hour box fills the whole columnMove them to a separate all-day row
Very short eventsA 10-minute item is 8 px tallMinimum visual height, used in the overlap check too
Current timeUsers lose their placeA "now" line updated every minute
Initial scrollThe view opens at midnightScroll the body to working hours

FullCalendar's TimeGrid view has options for most of these: allDaySlot for the all-day section, nowIndicator for the current-time marker, slotMinTime/slotMaxTime for the visible hours and slotEventOverlap for how overlapping events are drawn. That list is a good checklist for your own build.

Mapping Time to Pixels Without DST Bugs

The obvious calculation, (event.start - midnight) / 60000, gives elapsed minutes. On a day when the clocks spring forward, 10:00 is only nine hours after midnight, so the event is drawn on the 09:00 line. MDN's setDate() page describes the same effect: arithmetic in local time across a DST transition makes the elapsed time an hour shorter or longer than the number of days × 24 hours.

A week view shows wall-clock time, so position events by their wall-clock minutes:

const HOUR = 48; // px per hour const MIN_PX = HOUR / 60; // px per minute const DAY_MS = 86400000; const minutesIntoDay = (d) => d.getHours() * 60 + d.getMinutes(); function startOfDay(d) { const x = new Date(d); x.setHours(0, 0, 0, 0); return x; } function addDays(d, n) { const x = new Date(d); x.setDate(x.getDate() + n); // local calendar days, safe across DST return x; } function startOfWeek(d, weekStartsOn = 1) { const x = startOfDay(d); return addDays(x, -((x.getDay() - weekStartsOn + 7) % 7)); } // Which column (0–6) a date falls in. Math.round absorbs 23/25-hour days. const dayIndex = (d, weekStart) => Math.round((startOfDay(d) - weekStart) / DAY_MS);

There's one trade-off. On the spring-forward day the skipped hour (for example 02:00–03:00) still appears in the grid but nothing can start in it. On the fall-back day, two events in the repeated hour land on the same pixels. Every mainstream calendar accepts this, because the alternative is a grid with a 23- or 25-hour column.

Splitting Overnight and Multi-Day Events

An event from Wednesday 22:00 to Thursday 02:00 belongs in two columns. Rather than special-casing it in the renderer, turn every timed event into segments, one per day it touches, clipped to that day:

function splitByDay(event, weekStart, days = 7) { const segments = []; for (let i = 0; i < days; i++) { const dayStart = addDays(weekStart, i); const dayEnd = addDays(weekStart, i + 1); if (event.end <= dayStart || event.start >= dayEnd) continue; const segStart = event.start > dayStart ? event.start : dayStart; const segEnd = event.end < dayEnd ? event.end : dayEnd; segments.push({ event, day: i, top: minutesIntoDay(segStart), bottom: segEnd.getTime() === dayEnd.getTime() ? 1440 : minutesIntoDay(segEnd), continuesBefore: segStart > event.start, // clipped at the top continuesAfter: segEnd < event.end, // clipped at the bottom }); } return segments; }

The two continues* flags let you square off the clipped corners, which is the usual visual cue that an event carries on into the next column. Note the 1440 special case: a segment that ends exactly at midnight would otherwise get a bottom of 0.

Decide early which events count as timed at all. A common rule, and the one used below, is that anything flagged allDay or lasting 24 hours or more goes to the all-day row. A 48-hour on-call shift drawn as two full-height columns is technically accurate but hides everything else that week.

Need a calendar in your app?

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

Laying Out Overlapping Events in Columns

This is the core algorithm of every time grid. The version below is the column-packing approach most calendar apps use:

  1. Sort a day's segments by start time, longest first when starts tie.
  2. Walk the list, tracking a cluster: a run of segments connected by overlaps. When a segment starts at or after the cluster's latest end, the cluster is closed.
  3. Within a cluster, put each segment in the first column whose last segment has already ended; if none has, open a new column.
  4. When a cluster closes, every segment in it gets the same column count, so widths line up.
const MIN_EVENT = 20; // minutes: minimum visual height function layoutDay(segments) { const sorted = [...segments].sort( (a, b) => a.top - b.top || b.bottom - a.bottom ); let cluster = []; let columns = []; // columns[i] = visual bottom of the last segment in column i let clusterEnd = -1; const closeCluster = () => { for (const s of cluster) s.colCount = columns.length; cluster = []; columns = []; }; for (const seg of sorted) { const visualBottom = Math.max(seg.bottom, seg.top + MIN_EVENT); if (seg.top >= clusterEnd) { closeCluster(); clusterEnd = -1; } let col = columns.findIndex((end) => end <= seg.top); if (col === -1) { col = columns.length; columns.push(visualBottom); } else { columns[col] = visualBottom; } seg.col = col; seg.visualBottom = visualBottom; cluster.push(seg); clusterEnd = Math.max(clusterEnd, visualBottom); } closeCluster(); return sorted; }

Two details matter here. First, the overlap check uses the visual bottom, not the real end time. If a 10-minute standup is drawn 20 minutes tall, the next event must not be placed on top of the extra 10 minutes. Second, column count is per cluster, not per day. A 3-way clash at 09:00 shouldn't squeeze the lunch box at 12:00 to a third of the width.

Rendering is then simple arithmetic: left = col / colCount, width = 1 / colCount. A refinement you can add later is letting a segment expand right into empty columns. Google-style layouts also allow a slight overlap instead of strict side-by-side boxes, which is what FullCalendar's slotEventOverlap toggles.

The All-Day Row

All-day and multi-day events sit in a strip between the day headers and the scrolling body. They span whole days, so CSS Grid handles them well: give each event a grid-column range and pick a row with the same "first free slot" approach as the overlap layout:

// Exclusive end column: an end at local midnight doesn't occupy that day. function endIndex(end, weekStart) { const idx = dayIndex(end, weekStart); return minutesIntoDay(end) === 0 ? idx : idx + 1; } function layoutAllDay(events, weekStart) { const weekEnd = addDays(weekStart, 7); const rows = []; // rows[r] = first free day column in row r return events .filter((e) => e.end > weekStart && e.start < weekEnd) .sort((a, b) => a.start - b.start || (b.end - b.start) - (a.end - a.start)) .map((e) => { const from = Math.max(0, dayIndex(e.start, weekStart)); const to = Math.min(7, endIndex(e.end, weekStart)); let row = rows.findIndex((free) => free <= from); if (row === -1) { row = rows.length; rows.push(0); } rows[row] = to; return { event: e, from, to, row }; }); }

The exclusive end follows the convention most calendar data uses: an all-day event on Thursday and Friday ends at Saturday 00:00. If your API sends inclusive end dates, add one day before layout, or every multi-day event will be a day short.

Current Time Line and Scrolling to Working Hours

A now line is a 2 px absolutely positioned element inside today's column, moved every minute. It disappears when the visible week doesn't contain today:

const nowLine = document.createElement('div'); nowLine.className = 'now'; function placeNowLine(dayCols, weekStart) { const now = new Date(); const idx = dayIndex(now, weekStart); if (idx < 0 || idx > 6) return nowLine.remove(); nowLine.style.top = minutesIntoDay(now) * MIN_PX + 'px'; dayCols[idx].append(nowLine); }

For the initial position, set the scroll container's scrollTop. MDN notes that assigning it scrolls the element to that vertical position, the same as scroll() with behavior: "auto". body.scrollTop = 8 * HOUR opens the view at 08:00 without hiding the early hours. If you put the day headers inside the scroll container instead of above it, give them position: sticky; top: 0. Sticky elements stick to their nearest scrolling ancestor, which here is the grid body.

The Complete Example

Here is everything in one file. Save it as week.html and open it; it builds a week starting Monday with sample events covering each case above: a three-way clash, an overnight deploy, a two-day conference and a 48-hour on-call shift.

<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Week view</title> <style> :root { --hour: 48px; --gutter: 56px; } body { font: 14px system-ui, sans-serif; margin: 24px; } .wv { border: 1px solid #ddd; border-radius: 8px; overflow: hidden; } .wv-row { display: grid; grid-template-columns: var(--gutter) repeat(7, 1fr); } .wv-head > div { padding: 8px 4px; text-align: center; font-weight: 600; border-left: 1px solid #eee; } .wv-allday { grid-auto-rows: 24px; row-gap: 2px; padding: 4px 0; border-block: 1px solid #ddd; } .wv-allday .label { grid-column: 1; grid-row: 1; font-size: 11px; color: #777; text-align: right; padding-right: 6px; } .wv-allday .ev { position: static; margin: 0 2px; } .wv-body { height: 520px; overflow-y: auto; } .wv-hours > div { height: var(--hour); font-size: 11px; color: #777; text-align: right; padding-right: 6px; box-sizing: border-box; transform: translateY(-0.6em); } .wv-day { position: relative; height: calc(var(--hour) * 24); border-left: 1px solid #eee; background: repeating-linear-gradient(to bottom, #eee 0 1px, transparent 1px var(--hour)); } .ev { position: absolute; box-sizing: border-box; padding: 2px 4px; overflow: hidden; border: 1px solid #fff; border-radius: 4px; background: #4f46e5; color: #fff; font-size: 12px; } .ev.cut-top { border-top-left-radius: 0; border-top-right-radius: 0; } .ev.cut-bottom { border-bottom-left-radius: 0; border-bottom-right-radius: 0; } .now { position: absolute; left: 0; right: 0; height: 2px; background: #e11d48; z-index: 2; pointer-events: none; } </style> </head> <body> <div class="wv"> <div class="wv-row wv-head" id="head"></div> <div class="wv-row wv-allday" id="allday"></div> <div class="wv-body" id="body"><div class="wv-row" id="grid"></div></div> </div> <script> const HOUR = 48, MIN_PX = HOUR / 60, MIN_EVENT = 20, DAY_MS = 86400000; const minutesIntoDay = (d) => d.getHours() * 60 + d.getMinutes(); function startOfDay(d) { const x = new Date(d); x.setHours(0, 0, 0, 0); return x; } function addDays(d, n) { const x = new Date(d); x.setDate(x.getDate() + n); return x; } function startOfWeek(d, weekStartsOn = 1) { const x = startOfDay(d); return addDays(x, -((x.getDay() - weekStartsOn + 7) % 7)); } const dayIndex = (d, ws) => Math.round((startOfDay(d) - ws) / DAY_MS); function endIndex(end, ws) { const idx = dayIndex(end, ws); return minutesIntoDay(end) === 0 ? idx : idx + 1; } function el(tag, cls = '', text = '') { const n = document.createElement(tag); if (cls) n.className = cls; if (text) n.textContent = text; // textContent: no HTML injection from titles return n; } function splitByDay(event, ws) { const out = []; for (let i = 0; i < 7; i++) { const dayStart = addDays(ws, i), dayEnd = addDays(ws, i + 1); if (event.end <= dayStart || event.start >= dayEnd) continue; const s = event.start > dayStart ? event.start : dayStart; const e = event.end < dayEnd ? event.end : dayEnd; out.push({ event, day: i, top: minutesIntoDay(s), bottom: e.getTime() === dayEnd.getTime() ? 1440 : minutesIntoDay(e), continuesBefore: s > event.start, continuesAfter: e < event.end, }); } return out; } function layoutDay(segments) { const sorted = [...segments].sort((a, b) => a.top - b.top || b.bottom - a.bottom); let cluster = [], columns = [], clusterEnd = -1; const close = () => { for (const s of cluster) s.colCount = columns.length; cluster = []; columns = []; }; for (const seg of sorted) { const vb = Math.max(seg.bottom, seg.top + MIN_EVENT); if (seg.top >= clusterEnd) { close(); clusterEnd = -1; } let col = columns.findIndex((end) => end <= seg.top); if (col === -1) { col = columns.length; columns.push(vb); } else { columns[col] = vb; } Object.assign(seg, { col, visualBottom: vb }); cluster.push(seg); clusterEnd = Math.max(clusterEnd, vb); } close(); return sorted; } function layoutAllDay(events, ws) { const we = addDays(ws, 7), rows = []; return events .filter((e) => e.end > ws && e.start < we) .sort((a, b) => a.start - b.start || (b.end - b.start) - (a.end - a.start)) .map((e) => { const from = Math.max(0, dayIndex(e.start, ws)); const to = Math.min(7, endIndex(e.end, ws)); let row = rows.findIndex((free) => free <= from); if (row === -1) { row = rows.length; rows.push(0); } rows[row] = to; return { event: e, from, to, row }; }); } // Sample data for the current week const weekStart = startOfWeek(new Date(), 1); const at = (day, h, m = 0) => { const d = addDays(weekStart, day); d.setHours(h, m, 0, 0); return d; }; const events = [ { id: 1, title: 'Standup', start: at(0, 9), end: at(0, 9, 15) }, { id: 2, title: 'Design review', start: at(0, 9), end: at(0, 10, 30) }, { id: 3, title: 'Client call', start: at(0, 10), end: at(0, 11) }, { id: 4, title: 'Lunch', start: at(0, 12), end: at(0, 13) }, { id: 5, title: 'Deploy window', start: at(2, 22), end: at(3, 2) }, { id: 6, title: 'Conference', start: addDays(weekStart, 3), end: addDays(weekStart, 5), allDay: true }, { id: 7, title: 'On call', start: at(4, 8), end: at(6, 8) }, ]; const nowLine = el('div', 'now'); let dayCols = []; function placeNowLine(ws) { const now = new Date(), idx = dayIndex(now, ws); if (idx < 0 || idx > 6) return nowLine.remove(); nowLine.style.top = minutesIntoDay(now) * MIN_PX + 'px'; dayCols[idx].append(nowLine); } function render(ws) { const fmtDay = new Intl.DateTimeFormat(undefined, { weekday: 'short', day: 'numeric' }); const fmtHour = new Intl.DateTimeFormat(undefined, { hour: 'numeric' }); const fmtTime = new Intl.DateTimeFormat(undefined, { hour: 'numeric', minute: '2-digit' }); const inAllDayRow = (e) => e.allDay || e.end - e.start >= DAY_MS; document.getElementById('head').replaceChildren( el('div'), ...Array.from({ length: 7 }, (_, i) => el('div', '', fmtDay.format(addDays(ws, i)))) ); const allday = document.getElementById('allday'); allday.replaceChildren(el('div', 'label', 'all-day')); for (const b of layoutAllDay(events.filter(inAllDayRow), ws)) { const node = el('div', 'ev', b.event.title); node.style.gridColumn = `${b.from + 2} / ${b.to + 2}`; node.style.gridRow = String(b.row + 1); allday.append(node); } const hours = el('div', 'wv-hours'); for (let h = 0; h < 24; h++) hours.append(el('div', '', h ? fmtHour.format(new Date(2000, 0, 1, h)) : '')); dayCols = Array.from({ length: 7 }, () => el('div', 'wv-day')); document.getElementById('grid').replaceChildren(hours, ...dayCols); const segments = events.filter((e) => !inAllDayRow(e)).flatMap((e) => splitByDay(e, ws)); for (let i = 0; i < 7; i++) { for (const s of layoutDay(segments.filter((x) => x.day === i))) { const node = el('div', 'ev'); node.style.top = s.top * MIN_PX + 'px'; node.style.height = (s.visualBottom - s.top) * MIN_PX + 'px'; node.style.left = (s.col / s.colCount) * 100 + '%'; node.style.width = 100 / s.colCount + '%'; if (s.continuesBefore) node.classList.add('cut-top'); if (s.continuesAfter) node.classList.add('cut-bottom'); node.append(el('strong', '', s.event.title), el('div', '', fmtTime.format(s.event.start))); dayCols[i].append(node); } } placeNowLine(ws); } render(weekStart); document.getElementById('body').scrollTop = 8 * HOUR; // open at 08:00 setInterval(() => placeNowLine(weekStart), 60000); </script> </body> </html>

That comes to about 200 lines with no dependencies, and it handles the layout cases correctly. It does not include drag and drop, resizing, keyboard navigation, ARIA roles, loading data per visible range, or a narrow-screen layout. Each of those is a project of its own. Our drag and drop calendar guide covers why pointer handling across mouse, touch and scroll containers takes more work than it looks.

Building a Week View With SimpleCalendarJS

If you'd rather not maintain layout code, SimpleCalendarJS gives you a week view as one of its four views (month, week, day and list). It has zero dependencies and weighs ~14 KB gzipped (~19 KB with the CSS), and it works in vanilla JS or inside any framework's lifecycle hooks. Events come from a single async fetchEvents(start, end) function called with the visible range. Drag to move and drag to resize work with mouse and touch.

npm install simple-calendar-js
<div id="calendar" style="height: 640px"></div>
import SimpleCalendarJs from 'simple-calendar-js'; import 'simple-calendar-js/dist/simple-calendar-js.min.css'; const today = new Date(); const at = (dayOffset, h, m = 0) => new Date(today.getFullYear(), today.getMonth(), today.getDate() + dayOffset, h, m); let events = [ { id: 1, title: 'Design review', start: at(0, 9), end: at(0, 10, 30), color: '#4f46e5' }, { id: 2, title: 'Client call', start: at(0, 10), end: at(0, 11), color: '#0891b2' }, { id: 3, title: 'Deploy window', start: at(1, 22), end: at(2, 2), color: '#b45309', description: 'Freeze merges to main' }, { id: 4, title: 'Conference', start: at(3, 0), end: at(5, 0), allDay: true, color: '#059669' }, ]; const calendar = new SimpleCalendarJs('#calendar', { defaultView: 'week', enabledViews: ['week', 'day', 'list'], weekStartsOn: 1, use24Hour: true, locale: 'en-GB', enableDragDrop: true, enableResize: true, autoContrastText: true, fetchEvents: async () => events, onEventDrop: (event, oldStart, oldEnd, newStart, newEnd) => { events = events.map((e) => e.id === event.id ? { ...e, start: newStart, end: newEnd } : e ); calendar.refresh(); // persist to your API here as well }, onSlotClick: (date) => { const title = window.prompt('New event title'); if (!title) return; const end = new Date(date.getTime() + 60 * 60 * 1000); events = [...events, { id: Date.now(), title, start: date, end }]; calendar.refresh(); }, onEventClick: (event) => console.log('Open your edit form for', event.id), });

The time grid is themed with CSS custom properties, including the hour row height, the time gutter width and the color of the current-time line:

.uc-calendar { --cal-hour-height: 48px; --cal-time-col-width: 56px; --cal-now-color: #e11d48; --cal-primary: #4f46e5; }

For real data, replace the fixed array with a request that uses the start and end arguments. See loading calendar events from a REST API for a complete version. After you change data, call refresh(): it clears the per-month cache and calls fetchEvents again.

Here is what it doesn't do, so you can decide early:

  • No option to limit visible hours or hide weekends. If you need a 08:00–18:00, Monday–Friday grid, that's a reason to look elsewhere.
  • No recurring events. Expand weekly rules into individual events inside fetchEvents.
  • No timezone option. Dates appear in the browser's local time; convert before returning them.
  • No resource columns (one column per room or person) and no built-in event forms. onSlotClick and onEventClick are where you open your own.

SimpleCalendarJS is free for personal, educational and open source projects; client sites, SaaS products and internal company tools need a commercial license. You can try the week view with your own options in the sandbox or read the full option list in the docs.

Need a calendar in your app?

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

When Another Library Is the Better Fit

Choose by the shape of your week view, not by popularity:

You needBetter fit
A standard 7-day time grid, drag/resize, small bundle, any frameworkSimpleCalendarJS, or the hand-rolled version above
Visible-hour limits, configurable slot sizes, a fine-tuned overlap modeFullCalendar's TimeGrid plugin (slotMinTime, slotMaxTime, slotEventOverlap)
One column per room, staff member or machineEventCalendar's ResourceTimeGrid, or a commercial scheduler
A fully custom design with very few featuresYour own code, starting from the example above

EventCalendar (vkurko/calendar) deserves a mention here. It's MIT-licensed, inspired by FullCalendar's API, ships TimeGrid and ResourceTimeGrid views as plugins, and its standalone bundle is listed at about 39 KB compressed with Brotli with zero dependencies (as of 2026). If you need resource columns in a week view without paying for a license, check it first. For a broader ranking across scheduler use cases, see Best JavaScript Scheduler Libraries in 2026.

Sources & Further Reading

Image Credits

Image free to use under the Pexels License.

Frequently Asked Questions

How do I show only working hours in a JavaScript week view?

In a hand-rolled grid, render all 24 hours and set the scroll container's scrollTop to your start hour times the hour height, or render only the hours you need and subtract the start hour from every offset. FullCalendar has slotMinTime and slotMaxTime options for this. SimpleCalendarJS has no option to limit the visible hours.

What hour height should a week view use?

Somewhere between 40 and 60 px per hour works for most apps. At 48 px a 15-minute event is only 12 px tall, too small for a title, so give events a minimum visual height (20–30 minutes' worth) and use that height when you check for overlaps. In SimpleCalendarJS you set this with the --cal-hour-height CSS variable.

Should I use CSS Grid or absolute positioning for events in a week view?

Use both. CSS Grid works well for the frame: the time gutter, seven day columns and the all-day row, where events snap to whole days. Timed events need minute precision and partial widths for overlaps, so position them absolutely inside each relatively positioned day column, with top, height, left and width calculated in JavaScript.

How do I handle time zones in a week view calendar?

Pick one display zone and convert every event to it before layout, because getHours() and setDate() always use the browser's local zone. If users must see a different zone than their browser's, convert server-side or with a date library first. SimpleCalendarJS shows dates in the browser's local time and has no timezone option.

How do I show recurring weekly events in a week view?

Expand them into concrete occurrences for the visible range before layout. Loop from the range start to its end, create one event object per matching weekday with its own start and end, and give each occurrence a unique id. With SimpleCalendarJS, do this expansion inside fetchEvents, which receives the visible start and end dates.

Why does my week view put events an hour off on DST days?

You are probably computing the offset as (event - midnight) / 60000. On a daylight saving change day that difference is an hour more or less than the wall-clock time. Use date.getHours() * 60 + date.getMinutes() for the vertical position, and step days with setDate() rather than adding 86,400,000 ms.

Add a calendar to your app today

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

Keep Reading