Guide · 2026-11-21

Create a Gantt Chart in JavaScript: 5-Step Practical Guide

A Gantt chart can make a project timeline easier to understand, but building one in JavaScript can feel like a tangle of dates, widths, and overlapping task bars. A small calculation error may place a task on the wrong day, while a chart that looks fine on a laptop can become unreadable on a narrow screen. You do not need a large charting library to get started. With a task list, a date scale, and a few DOM elements, you can create a working Gantt chart in plain JavaScript. This guide walks you through five practical steps, from preparing task dates to adding readable progress bars. You’ll also see a complete example you can adapt to your own project.

How to Create a Gantt Chart in JavaScript: Five Steps

The simplest way to create a Gantt chart in JavaScript is to store each task with a start date, an end date, and optional progress, then render each task as a bar on a shared timeline.

Here’s the five-step approach: define the tasks, calculate the timeline, build the chart layout, draw task bars, and check the result for usability.

Step 1: Define tasks with clear dates

Start with a JavaScript array. Give each task a unique ID, a readable name, a start date, an end date, and a progress value.

const tasks = [
  {
    id: "research",
    name: "Research",
    start: "2025-04-01",
    end: "2025-04-04",
    progress: 100
  },
  {
    id: "design",
    name: "Design",
    start: "2025-04-03",
    end: "2025-04-08",
    progress: 60
  },
  {
    id: "build",
    name: "Build",
    start: "2025-04-09",
    end: "2025-04-16",
    progress: 20
  }
];

Use the same date format for every task. ISO-style dates such as 2025-04-01 are easy to inspect and parse consistently.

For this example, the end date is inclusive. A task that starts and ends on April 1 occupies one day, not zero days.

Step 2: Calculate the timeline scale

Find the earliest task start and latest task end. Their difference determines the number of calendar days the chart needs to show.

JavaScript dates can shift when local time zones apply. Parsing the date parts with UTC avoids off-by-one surprises in this example.

const DAY_MS = 24 * 60 * 60 * 1000;

function parseDate(value) {
  const [year, month, day] = value.split("-").map(Number);
  const date = new Date(Date.UTC(year, month - 1, day));

  if (
    date.getUTCFullYear() !== year ||
    date.getUTCMonth() !== month - 1 ||
    date.getUTCDate() !== day
  ) {
    throw new Error(`Invalid date: ${value}`);
  }

  return date;
}

function getTimeline(tasks) {
  if (tasks.length === 0) {
    throw new Error("Add at least one task.");
  }

  const dates = tasks.flatMap(task => [
    parseDate(task.start),
    parseDate(task.end)
  ]);

  const firstDay = Math.min(...dates);
  const lastDay = Math.max(...dates);
  const dayCount = Math.round((lastDay - firstDay) / DAY_MS) + 1;

  return { firstDay, dayCount };
}

The extra + 1 includes the final date. Without it, a one-day task would have no visible width.

Step 3: Create a scrollable chart layout

A useful basic layout has one column for task names and another for the timeline. Give each day a fixed width, then allow horizontal scrolling when the timeline is wider than the screen.

Add a chart container to your page:

<div id="gantt-chart"></div>

Then add CSS for the header, task rows, timeline cells, and bars:

#gantt-chart {
  --label-width: 180px;
  --day-width: 44px;
  font-family: Arial, sans-serif;
}

.gantt-scroll {
  overflow-x: auto;
  border: 1px solid #d6dbe1;
}

.gantt {
  width: max-content;
  color: #202833;
}

.gantt-header,
.gantt-row {
  display: grid;
  grid-template-columns: var(--label-width) auto;
}

.gantt-label,
.gantt-task-name {
  box-sizing: border-box;
  width: var(--label-width);
  padding: 10px;
  border-right: 1px solid #d6dbe1;
  border-bottom: 1px solid #d6dbe1;
}

.gantt-header {
  font-weight: 700;
  background: #f3f5f7;
}

.gantt-track {
  position: relative;
  display: grid;
  grid-auto-columns: var(--day-width);
  grid-auto-flow: column;
  min-height: 44px;
}

.gantt-day {
  box-sizing: border-box;
  width: var(--day-width);
  padding: 10px 4px;
  text-align: center;
  border-right: 1px solid #d6dbe1;
  border-bottom: 1px solid #d6dbe1;
  font-size: 12px;
}

.gantt-bar {
  position: absolute;
  top: 9px;
  height: 26px;
  overflow: hidden;
  border-radius: 5px;
  background: #c8d8f4;
}

.gantt-progress {
  height: 100%;
  background: #356ac3;
}

.gantt-bar-label {
  position: absolute;
  inset: 0;
  padding: 5px 8px;
  overflow: hidden;
  color: #142744;
  font-size: 12px;
  white-space: nowrap;
}

For the bar, the chart will calculate a horizontal offset and width from the task dates. Keeping each day the same width makes that math straightforward.

Step 4: Render the dates, task rows, and bars

The renderer below creates a calendar-day header and one row per task. It uses textContent for task names, so names are treated as text rather than markup.

const DAY_MS = 24 * 60 * 60 * 1000;
const DAY_WIDTH = 44;

function parseDate(value) {
  const [year, month, day] = value.split("-").map(Number);
  const date = new Date(Date.UTC(year, month - 1, day));

  if (
    date.getUTCFullYear() !== year ||
    date.getUTCMonth() !== month - 1 ||
    date.getUTCDate() !== day
  ) {
    throw new Error(`Invalid date: ${value}`);
  }

  return date;
}

function renderGantt(container, tasks) {
  if (!container) {
    throw new Error("Chart container was not found.");
  }

  if (tasks.length === 0) {
    container.textContent = "Add at least one task to show the timeline.";
    return;
  }

  const seenIds = new Set();

  tasks.forEach(task => {
    if (seenIds.has(task.id)) {
      throw new Error(`Task IDs must be unique: ${task.id}`);
    }
    seenIds.add(task.id);

    const start = parseDate(task.start);
    const end = parseDate(task.end);

    if (end < start) {
      throw new Error(`End date comes before start date for ${task.name}.`);
    }

    if (!Number.isFinite(task.progress) || task.progress < 0 || task.progress > 100) {
      throw new Error(`Progress must be between 0 and 100 for ${task.name}.`);
    }
  });

  const allDates = tasks.flatMap(task => [
    parseDate(task.start).getTime(),
    parseDate(task.end).getTime()
  ]);

  const firstDay = Math.min(...allDates);
  const lastDay = Math.max(...allDates);
  const dayCount = Math.round((lastDay - firstDay) / DAY_MS) + 1;

  const scroll = document.createElement("div");
  scroll.className = "gantt-scroll";

  const chart = document.createElement("div");
  chart.className = "gantt";
  chart.style.setProperty("--day-width", `${DAY_WIDTH}px`);

  const header = document.createElement("div");
  header.className = "gantt-header";

  const headerLabel = document.createElement("div");
  headerLabel.className = "gantt-label";
  headerLabel.textContent = "Task";
  header.append(headerLabel);

  const headerTrack = document.createElement("div");
  headerTrack.className = "gantt-track";

  for (let offset = 0; offset < dayCount; offset++) {
    const date = new Date(firstDay + offset * DAY_MS);
    const dayCell = document.createElement("div");
    dayCell.className = "gantt-day";
    dayCell.textContent = `${date.getUTCMonth() + 1}/${date.getUTCDate()}`;
    headerTrack.append(dayCell);
  }

  header.append(headerTrack);
  chart.append(header);

  tasks.forEach(task => {
    const row = document.createElement("div");
    row.className = "gantt-row";

    const name = document.createElement("div");
    name.className = "gantt-task-name";
    name.textContent = task.name;

    const track = document.createElement("div");
    track.className = "gantt-track";

    for (let offset = 0; offset < dayCount; offset++) {
      const cell = document.createElement("div");
      cell.className = "gantt-day";
      cell.setAttribute("aria-hidden", "true");
      track.append(cell);
    }

    const start = parseDate(task.start).getTime();
    const end = parseDate(task.end).getTime();
    const offset = Math.round((start - firstDay) / DAY_MS);
    const duration = Math.round((end - start) / DAY_MS) + 1;

    const bar = document.createElement("div");
    bar.className = "gantt-bar";
    bar.style.left = `${offset * DAY_WIDTH}px`;
    bar.style.width = `${duration * DAY_WIDTH - 4}px`;
    bar.setAttribute(
      "aria-label",
      `${task.name}, ${task.start} to ${task.end}, ${task.progress}% complete`
    );
    bar.setAttribute("role", "img");

    const progress = document.createElement("div");
    progress.className = "gantt-progress";
    progress.style.width = `${task.progress}%`;

    const label = document.createElement("span");
    label.className = "gantt-bar-label";
    label.textContent = `${task.name} — ${task.progress}%`;

    bar.append(progress, label);
    track.append(bar);
    row.append(name, track);
    chart.append(row);
  });

  scroll.append(chart);
  container.replaceChildren(scroll);
}

renderGantt(document.getElementById("gantt-chart"), tasks);

In the example, a task starting three days after the timeline begins gets an offset of three day-widths. Its bar width is the number of inclusive days multiplied by the same width.

Step 5: Check the chart with real project cases

Try overlapping dates, a one-day task, a task at the timeline’s final date, and progress values of 0 and 100. Each case should remain visible and correctly aligned.

For example, a task from April 3 through April 8 should span six calendar cells. A task that ends before it starts should trigger a clear validation error rather than render incorrectly.

When you add features such as drag-to-reschedule or dependency lines, keep the same date calculations as the basis for visual placement. That way, the chart and task details stay in sync.

Choose the Right Rendering Approach

For a small timeline, HTML and CSS are often enough. You can build task rows with elements and position bars using CSS, as in the example above.

SVG is a good fit when you need precise shapes, connector arrows, or custom drawing. Canvas can handle many visual marks efficiently, though it takes extra work to make individual tasks accessible and interactive.

Here’s why: the best rendering method depends on how people need to use the chart. A team tracking twelve tasks may value simple keyboard access more than animated dependency lines.

When a library can help

A JavaScript Gantt library may save time if your project needs dependency editing, zoom controls, drag-and-drop scheduling, or established export options.

Before choosing one, check its licensing, accessibility, customization options, and maintenance activity. If your chart only needs static task bars, a small custom implementation can be easier to adapt.

Make Dates and Workdays Behave as Expected

The example uses calendar days, so weekends appear in the timeline. That may suit a release plan, but it can misrepresent a schedule measured in working days.

For a Monday-to-Friday work calendar, generate visible dates by advancing one day at a time and skipping weekends. Then calculate each task’s position against that generated calendar rather than dividing elapsed milliseconds by one day.

Let me explain: calendar time and working time answer different questions. A task that spans Friday to Monday occupies four calendar dates, but usually only two workdays.

Handle time zones and date boundaries

Keep date-only values separate from timestamps when tasks do not need a time of day. A timestamp such as 2025-04-01T00:00:00 can behave differently across time zones.

If your schedule includes hours, decide which time zone governs the project and use a consistent time model throughout parsing, display, and editing. Mixing local dates with UTC calculations can shift bars unexpectedly.

Improve Usability, Accessibility, and Performance

A chart is useful only when people can read it. Keep task names visible, use strong contrast, and avoid relying on color alone to communicate completion.

The example includes task names and progress percentages inside the bars, plus an accessible label for each bar. For keyboard interaction, make editable bars focusable and provide visible focus styling.

You might be wondering: what happens when a project has hundreds of tasks? Start by rendering only the visible rows or grouping tasks into phases. For a few dozen rows, straightforward DOM rendering may be sufficient.

Give the timeline useful controls

Consider adding controls for zooming between day, week, and month views. A date range that works for a two-week sprint can become unwieldy across a year-long program.

Show the chosen range clearly, and let people move to the current date or a selected milestone. When someone changes a task date, update its bar and accessible label together.

Project and Knowledge Management with ONES.com

ONES.com brings project management and knowledge management together in one platform powered by ONES Assistant. ONES Project handles project management, while ONES Wiki provides a knowledge base; the two are sold separately.

ONES.com product screenshot

If your JavaScript chart is one part of a larger delivery workflow, ONES.com can help coordinate tasks, team processes, and project knowledge. ONES Project is a Jira alternative with Jira-compatible workflows, built-in reporting, custom workflows and fields, sprint management, and automation.

Core capabilities

ONES.com offers a free plan for up to 30 seats. ONES Project and ONES Wiki are available as separate products, so you can choose the capabilities that fit your team.

Application scenarios

Software release planning: A team can manage sprint work in ONES Project while a JavaScript Gantt chart gives stakeholders a calendar-oriented view of major milestones. The chart can show phase timing without replacing the team’s task workflow.

Restricted hosting environments: An organization that cannot use a public cloud deployment can consider On-Premise, Private Cloud, or Air-gapped options. It can coordinate project work while keeping deployment aligned with its environment.

Project handoffs: A delivery team can use ONES Project to manage task ownership and ONES Wiki for team guidance. Since the products are sold separately, teams can select either or both according to their needs.

Common Challenges When Building a Gantt Chart

Frequently Asked Questions

Can I create a Gantt chart in JavaScript without a library?

Yes. For a basic chart, JavaScript can create the task rows and date labels, while CSS positions each bar. This approach works well when you need a clear timeline with a small set of interactions. A library may be useful when you need advanced editing, dependency management, or multiple zoom levels without building those features yourself.

How do I calculate a Gantt bar’s position?

Find the number of days between the timeline’s first date and the task’s start date. Multiply that offset by the width of one day to get the bar’s left position. Calculate the inclusive task duration, then multiply it by the same day width to get the bar’s width. For non-working-day schedules, calculate offsets against a workday calendar instead.

Should a Gantt chart show weekends?

That depends on the schedule. Calendar-day charts are simple and suit plans where every date matters, such as event schedules or release windows. Workday charts are often clearer for team tasks that pause over weekends. Pick one convention, label it clearly, and use the same rule for date placement and task duration.

How can I make a JavaScript Gantt chart accessible?

Use readable task names, sufficient color contrast, and text labels that communicate progress. Add accessible labels to bars, and support keyboard focus if people can edit the timeline. Avoid using color as the only status signal. For a canvas-based chart, provide a meaningful alternative representation of the tasks, because individual marks are not automatically exposed like regular page elements.

When should I use SVG or Canvas instead of HTML and CSS?

HTML and CSS are a practical starting point for task rows and straightforward bars. SVG can make custom shapes, connectors, and precise interactions easier to manage. Canvas may be appropriate when a chart contains many visual marks, but it needs additional accessibility work. Choose the approach that matches your chart’s interaction needs and the number of tasks it must display.

Conclusion

You can build a useful JavaScript Gantt chart by defining consistent task dates, calculating a shared timeline, and rendering each task as an inclusive bar. Add validation before rendering, then check overlaps, one-day tasks, progress values, and narrow screens.

Start with the smallest chart that answers your project question. If task coordination grows beyond the visualization, a project workflow platform such as ONES.com may help organize delivery work and related team knowledge.

Dates and layout can be frustrating when they are handled inconsistently. A clear date model, a simple rendering approach, and a few practical checks give you a dependable foundation to expand.