How to use
MZGantt supports two usage methods: JS reference and npm installation.
1. Download
Before use, download the standard JS version plugin or install it via npm.
Standard JS version: [MZGantt Gantt Chart Plugin (Standard JS Version)](download link)
NPM version (supports Vue, etc.): Install directly using the npm command.
npm i mzgantt
Reference MZGantt Plugin
Add the following JS packages in the head section of your HTML page:
- Standard JS Reference
<!-- Include the Gantt chart plugin -->
<link rel="stylesheet" type="text/css" href="./gantt/mzgantt.css" />
<script language="javascript" src="./gantt/mzgantt.js"></script>
<script language="javascript" src="./gantt/edit.js"></script>
- NPM Reference
// Import MZGantt package. There are several packages, import as needed:
// 1. Basic package: MZGantt (must include. Contains basic Gantt chart display functions)
// 2. Editing package: MZGanttEditor (optional. Contains Gantt chart editing functions)
// 3. Export package: MZGanttExport (optional. Contains Gantt chart export functions)
// 4. Mobile support package: MZGanttMobile (optional. Contains mobile support functions)
import {MZGantt, MZGanttEditor} from './mzgantt';
// Get and set the license key(Copy the license key text content below without line breaks or formatting, then remove the comment symbols to activate the license code)
// var _0x1d51=['constructor','1174609hyFUnm','return\x20/\x22\x20+\x20this\x20+\x]
Define Gantt Chart Container(div)
Define a div in the HTML page to display the Gantt chart:
<div id="GanttChartDIV" style="width:100%;"></div>
Define Gantt Chart Parameters
This step is optional. If you do not define parameters, the plugin will use default values. To customize the Gantt chart display, you can set various parameters. Some configurable parameters are as follows:
var ganttConfig = {
useFor: "Task", // Set Gantt chart purpose: 'Resource' for resource management (e.g., meeting room management); 'Task' for task management (e.g., planning and progress management). Default: Task
ganttStatus: "e", // Set Gantt chart status (e: edit plan, r: read-only)
// Table column configuration (left-side table columns configuration, not Gantt chart data format)
// Note: If you need to change the planned dates by dragging, planStart, planEnd, and planDur must be defined here,
// if you do not want to display these columns, you can configure them to be hidden (visible: false), otherwise, there may be an issue where the progress bar returns to its original position after being dragged.
columnDefs: [
{name: 'seq', field: "seq", type:"level"},
{name: 'checkbox', field: "checkbox"},
{name: 'iconColsVal', field: "iconColsVal", width: 30},
// The following fields, the name can be customized, and must correspond to the respective item names in the data. The field value is fixed and cannot be reset, and does not support setting type.
{name: 'name', field: "name", title: "Task Name", width: 150},
{name: 'resId', field: "resId", title: "Responsible", width: 50, options: resourceList},
{name: 'dur', field: "dur", title: "Duration", width: 60},
{name: 'planStart', field: "planStart", title: "Planned Start", width: 120, editable: false},
{name: 'planEnd', field: "planEnd", title: "Planned End", width: 120, colCallBack:custCallbackFunc1},
{name: 'planDur', field: "planDur", title: "Planned Workdays", width: 60},
{name: 'rsltStart', field: "rsltStart", title: "Actual Start", width: 120},
{name: 'rsltEnd', field: "rsltEnd", title: "Actual End", width: 120},
{name: 'rsltDur', field: "rsltDur", title: "Actual Workdays", width: 60},
{name: 'pctComp', field: "pctComp", title: "Completion", width: 60},
// {name: 'caption', field: "caption", title: "Label Text"},
// Custom columns (field: "custColsVal"): Supports setting type: DropDownList/TextBox
// roperty altText: Custom column display text replacement
{name:"testCol1", field: "custColsVal", title:"Column 1", type: "TextBox", default: 10, width:50,align:"left"},
{name:"testCol2", field: "custColsVal", title:"Column 2", type: "DropDownList", options:dropDownListData, width:100, align:"left"},
{name:"testCol3", field: "custColsVal", title:"Column 3","width":150,"align":"left", colCallBack:custCallbackFunc2, altText: "查看图文"}
],
// Gantt chart display control
showTrack: 1, // 0: Planned Gantt chart; 1: Actual Gantt chart. Default: Planned Gantt chart.
showDuplicate: 0, // Whether to display resource overlap flag
showMileStone: 1, // Whether to display milestones: not displayed
showDependencies: 1, // Whether to display connection lines (0/1), default: 0 not displayed.
showDayDate: "date", // Set day format display: week or date (day: week; date: date). Default: day (display week).
showWeekIndex: "", // Set the first line display when in day format: week number or first date of the week. Y: display week number, others: display date. Default display date.
autoSelect: 1, // Set whether to automatically select the first row after loading. Default: 1 (select), 0 (do not select)
showMobileTools: 1, // Set whether to display the operation toolbar on mobile devices
showInfoBox: 1, // Whether to display the bar infomation box (0/1). Default 1: display, 0: none
showContextMenu: 1, // Whether to display the contextmenu (0/1). Default 1: display, 0: none
// Data definition===============================================================================
weekWorkSetting: // Weekly workday setting (D1: Monday ... D0: Sunday. 1: Workday, 0: Rest day)
{D1:1, D2:1, D3:1, D4:1, D5:1, D6:0, D0:0},
holidayList: [ // // Holiday list. If weekends are normally displayed, the dates in this list are added as holidays and displayed in gray.
'2023-02-09',
'2023-02-21~2023-02-25', // Supports setting date ranges: use the half-width symbol "~" as a separator.
'2023-03-20'],
workdayList: ['2023-03-18'], // Workday list
mileStoneLines: [ // Milestone configuration
{date:'2023-11-05',name:'startMS', title:'Project Design Discussion', color:'#FF00BF', thickness: "2px"},
{date:'2023-11-25',name:'pjMeeting', title:'Code Review', color:'#088A29', thickness: "2px"},
{date:'today',name:'today', title:'Today', color:'#FF0000', thickness: "2px"}
{date:'now',name:'now', title:'now', color:'#FF0000', thickness: "2px"}
],
workingHourSetting: [ // Set the daily working hours in case of hour format. Default: 1,23.
['7', '19']
],
onlyShowWorkhours: "Y", // Display only working hours (Y: Display only working hours; N: Display all hours. Default: N)
pastTimeStyle: "background:#cccccc;font-weight: bold;", // Set the backgroud for past time, default is gray.
contentMenus: [ // right-click context menu
{
name: 'mymenu1',
text: 'My Menu 1',
func: (row) => {
console.log("Click My Menu 1");
}
},
{
name: 'mymenu2',
text: 'My Menu 2',
icoFile: 'images/clone.png',
func: (row) => {
console.log("Click My Menu 2");
}
}
],
// Plugin configuration===============================================================================
captionType: 'Caption', // Set Gantt chart title (None, Name, Caption, Resource, Duration, Complete, Reserver, Title, Theme) None: do not display title
captionPosition: 'Right', // Set Gantt chart title display position (Over: above the Gantt chart bar; Center: center of the bar;Right: right side of the Gantt chart bar, default Over)
// Display date format and input date format should be unified
dateFormat: 'yyyy-mm-dd', // Set parameter date format ('mm/dd/yyyy', 'dd/mm/yyyy', 'yyyy-mm-dd', 'yyyy/mm/dd')
weekStartDay: 0, // Set the first day of the week (1: start on Monday; 0: start on Sunday), default: 0
workingHourRange: ['1','23'], // Set the daily working hours range in hour format. (in hours). Default: 1, 23.
hourFormat: 0, // Set hour format (0: hour without :00; 1: hour with :00). Default: 0 (display week).
dragChgDur: "1", // Set drag change duration. If showChgDur is set to not display, this option setting is invalid.
autoCalDur: 1, // Set automatic calculation of workdays (default not automatic)
includeHoliday: "N", // Whether to include holidays and weekends in workday calculation: Y: Include; N: Do not include
durPrecision: 2, // Set the precision of duration and workdays (default to one decimal place)
fixColsCnt: 3, // Set the number of fixed columns, default: 0 (no fixed columns)
fixParent: 1, // Fixed parent task plan-range (1: does not change with sub-task dragging; 0: changes with sub-task dragging)
idType: "Snow", // Task ID calculation method (default: 12 random characters; UUID: uuid; Snow: snowflake ID)
// Style control ===============================================================================
// Background color settings
// planBackground: vPlanBackground, // Set the background of the Gantt chart plan bar
// resultBackground: vResultBackground, // Set the background of the Gantt chart result bar
compBackground: '#0000FF', // Set the completion background
// groupBackground: '#00FF00', // Set the parent task row background
holidayBGColor: '#E6E6E6', // Set the background for holidays/vacation days
currentTimeBackColor: ['h','#FF9797'], // Set the background for the current time
// Parameter 1: h: Display the current time by setting the header style
// c: Display the current time by setting the content cell style
// Parameter 2: Color value
intervalColor: ['#FFFFFF','#F4F4F4'], // Set the background color for alternating rows, default: #FFFFFF,#F4F4F4
selectedRowColor: '#CAE1FF', // Set the background color for the selected row, default: #CAE1FF
selectedCellColor: '#2E9AFE', // Set the border color for the selected cell, default: #2E9AFE
borderColor: '#9E9E9E', // Set the border color for the Gantt chart, default: #9E9E9E
// Gantt chart bars
barBorderRadius: 6, // Set the border radius for Gantt chart bars, default: 3px
barBorderWeight: 1, // Set the border thickness for Gantt chart bars, default: 1px
barBorderColor: '#9E0000', // Set the border color for Gantt chart bars, default: #9E9E9E
barOpacity: 1, // Set the opacity for Gantt chart bars, default: 0.7
barGridBorderWeight: 1, // Set the border thickness for the background of Gantt chart bars, default: 1px
resultBarStyle: 'mark', // Result bar style (normal: do not mark dates outside the plan, mark: mark dates outside the plan; cust: custom segments)
markResultBarColor: // Result bar background color when the style is mark
{beforePlanBGColor: '#00FF00',
exceedPlanDBColor: '#cc0000'},
barHeightAdj: 0, // Progress bar height adjustment (default 0px, no adjustment; the larger the value, the higher the progress bar. Can be negative)
barDistanceAdj: 0, // Distance adjustment between the planned progress bar and the actual progress bar
// Default 0px, no adjustment; the larger the value, the closer the distance. Can be negative.
// Drag bar
dragHandlerBackColor: '#D8D8D8', // Drag bar background color
// lineExpandLen: 0, // Dependency line extension parameter
dependLineColor: '#228B22', // Connection line color
dependLineMouseOverColor: '#FE9A2E', // Connection line mouse hover color
criticalPathBGColor: '#FE9A2E', // Critical path marker color
// Width and height settings
leftSideWidth: 300, // Set the width of the left frame, default: 300px
contentHeight: 360, // Set the height of the Gantt chart (excluding the header), default: 300px
// If the adjustGanttHeight function is called on the page to make the Gantt chart height adaptive, this parameter may not be set.
rowHeight: 35, // Set the row height, default: 35px
// Left column width settings, can be discarded after columnDefs is improved
iconColWidth: 30, // Set the icon column width, default: 60px
nameColWidth: 150, // Set the task/resource column width, default: 150px
dateColWidth: 120, // Set the date column width, default: 80px
// Right cell width settings (for different time scales)
hourColWidth: 20, // Hour scale
dayColWidth: 20, // Day scale
monthColWidth: 70, // Month scale
quarterColWidth: 100 // Quarter scale
};
Fetch data from the backend, or define data
/*
Description of Gantt Chart Data Object Items:
a:Built-in fixed data items, cannot customize other names.
1. id // (Required) String Node ID (any string or number, must be unique)
2. plan // (Optional) Array Plan data
3. isExpand // (Optional) Number (0 or 1) Whether to expand display 1: expand / 0: collapse
4. isGroup // (Optional) Number (0 or 1) Whether to set as parent (group) 1: group / 0: leaf node
5. preNodes // (Optional) String|Array Predecessor nodes, use commas to separate multiple predecessor nodes
6. parentId // (Optional) String Parent node ID (if the current row is the top-level node, this value must be set to empty \"\")
7. isMS // (Optional) Number (0 or 1) Whether it is a milestone
8. caption // (Optional) String Title
9. planBarColor // (Optional) String Gantt chart plan background (color value)
b:The following data items can use custom names, which must match the name in the column definition.
10. name // (Required) String Name (can be used as task name, resource name, etc.)")
11. iconColsVal // (Optional) Array Icon columns (can be multiple icons separated by commas)
12. rsltStart // (Optional) String Date Actual start
13. rsltEnd // (Optional) String Date Actual completion
14. rsltDur // (Optional) Number Actual man-days
15. custColsVal // (Optional) String Custom column values need to correspond one-to-one with custom column configuration.
16. resId // (Optional) String Resource/Person in charge
17. pctComp // (Optional) Number Completion percentage (0 ~ 100%)
18. seq // (Optional) Decimal Sort orde
*/
// Gantt chart data
let ganttData= [
{
"id": 1,
"seq": 1000,
"iconColsVal": [],
"name": "Unit A during construction",
"plan": [{}],
"rsltStart": "",
"rsltEnd": "",
"rsltDur": 1,
"planBarColor": "",
"isMS": 0,
"resId": "1",
"pctComp": 0,
"isGroup": 1,
"parentId": "",
"isExpand": 1,
"preNodes": "",
"caption": "Focus on",
"testCol1": "10",
"testCol2": "02",
"testCol3": "<img src='./images/stop.png'>",
}, {
"id": 11,
"seq": 2000,
"iconColsVal": [{
"src": "./images/stop.png",
"title": "stop"
}
],
"name": "Task Name 1",
"plan": [{
"start": "",
"end": "",
"dur": "2"
}
],
"rsltStart": "2023-07-02",
"rsltEnd": "2023-07-06",
"rsltDur": 1,
"planBarColor": "#2EFE9A",
"isMS": 0,
"resId": "2",
"pctComp": 50,
"isGroup": 0,
"parentId": 1,
"isExpand": 1,
"preNodes": "",
"caption": "",
"testCol1": "1",
"testCol2": "02",
"testCol3": "",
"custRsltBars": [
{
name: "p1",
title: "Subsection 1",
start: "2023-07-02",
end: "2023-07-04",
style: "background:#2E9AFE;color:#FFFFFF;text-align:left;"
}, {
name: "p2",
title: "Subsection 2",
start: "2023-07-06",
end: "2023-07-17",
html: "<span style='height:7px;border-radius:5px 5px;" +
" position:absolute;left:5px;top:-1px;background:red;" +
" font-size:9px;color:#FFFFFF'>Beautiful</span>",
style: "background:#FF0000;color:#FFFFFF;text-align:left;"
},
],
}, {
"id": 12,
"seq": 3000,
"iconColsVal": [],
"name": "Task Name 2",
"plan": [{
"start": "2023-07-06",
"end": "2023-07-10"
}
],
"rsltStart": "2023-07-07",
"rsltEnd": "2023-07-10",
"rsltDur": 1,
"planBarColor": "#2EFE9A",
"isMS": 0,
"resId": "2",
"pctComp": 10,
"isGroup": 0,
"parentId": 1,
"isExpand": 1,
"preNodes": "",
"caption": "Remark1",
"testCol1": "1",
"testCol2": "03",
"testCol3": "",
}, {
"id": 13,
"seq": 4000,
"iconColsVal": [{
"src": "./images/star.png",
"title": "Star"
}
],
"name": "Task Name 3",
"plan": [{
"start": "2023-07-11",
"end": "2023-07-15"
}
],
"rsltStart": "2023-07-11",
"rsltEnd": "2023-07-14",
"rsltDur": 1,
"planBarColor": "#2EFE9A",
"isMS": 0,
"resId": "2",
"pctComp": 20,
"isGroup": 0,
"parentId": 1,
"isExpand": 1,
"preNodes": 12,
"caption": "",
"testCol1": "50",
"testCol2": "01",
"testCol3": "",
}, {
"id": 14,
"seq": 5000,
"iconColsVal": [],
"name": "Task Name 4",
"plan": [{
"start": "",
"end": "2023-07-17"
}
],
"rsltStart": "2023-07-16",
"rsltEnd": "2023-07-17",
"rsltDur": 1,
"planBarColor": vPlanBackground,
"isMS": 0,
"resId": "2",
"pctComp": 0,
"isGroup": 0,
"parentId": 1,
"isExpand": 1,
"preNodes": "",
"caption": "",
"testCol1": "20",
"testCol2": "01",
"testCol3": "",
},
{
"id": 2,
"seq": 6000,
"iconColsVal": [],
"name": "Unit B during construction",
"plan": [{}
],
"rsltStart": "",
"rsltEnd": "",
"rsltDur": 1,
"planBarColor": "",
"isMS": 0,
"resId": "1",
"pctComp": 0,
"isGroup": 1,
"parentId": "",
"isExpand": 1,
"preNodes": "",
"caption": "",
"testCol1": "4",
"testCol2": "01",
"testCol3": "<img src='./images/stop.png'>",
}, {
"id": 21,
"seq": 7000,
"iconColsVal": [{
"src": "./images/stop.png",
"title": "Stop"
}
],
"name": "Task Name 1",
"plan": [{
"start": "2023-07-19",
"end": "2023-07-29"
}
],
"rsltStart": "2023-07-26",
"rsltEnd": "2023-07-29",
"rsltDur": 1,
"planBarColor": vPlanBackground,
"isMS": 0,
"resId": "2",
"pctComp": 40,
"isGroup": 0,
"parentId": 2,
"isExpand": 1,
"preNodes": "",
"caption": "",
"testCol1": "4",
"testCol2": "02",
"testCol3": "",
},
......
];
Create Gantt Chart Object
// Instantiate Gantt Chart Object
const myGantt = MZGantt.init();
// Start functional modules
// Start Gantt Chart Editing
MZGanttEditor.start(myGantt);
// Start Export Function
MZGanttExport.start(myGantt);
/*
Create and Display Gantt Chart
Parameter 1: (Required) Container div object id
Parameter 2: (Optional) Time scale type
Parameter 3: (Optional) Configuration options
Parameter 4: (Optional) Data
*/
myGantt.createGantt("GanttChartDIV", "day");
// Note: If ganttConfig and data are set here, configuration and data binding methods can be used independently
// Gantt Chart Parameter Configuration
myGantt.config(ganttConfig);
// Load the data
myGantt.bindGanttData(data);
// Gantt Chart display
myGantt.drawGantt()
Listen to Events
MZGantt supports listening to render or click events, which can be used to achieve special control effects.
// Cell Rendering
myGantt.on("cellRender", function (row, cellObj) {
// *******************************************************
// You can control the rendering of the following types of cells (fields) in the Gantt chart's left table::
// 1. Built-in type columns::
// name Name
// iconColsVal Icon columns
// resId Resource/Person in charge
// planStart Planned start
// planEnd Planned completion
// planDur Planned man-days
// rsltStart Actual start
// rsltEnd Actual completion
// rsltDur Actual workdays
// pctComp Completion percentage
// 2. Custom columns
// testCol1 Custom column name (name)
// *******************************************************
// Get Cell Name (Render Object Cell)
var field = cellObj.field;
// Define the render style object
var cellStyle = {};
// Style setting: Task name
if (field == "name") {
if (row.plan[0].dur > 5) {
cellStyle["cellHTML"] = '<span style="color:red;" >' + row.name + '</span>';
// cell.style.color = "red";
}
if (row.plan[0].dur >= 2 && row.plan[0].dur <= 5) {
cellStyle["cellHTML"] = '<span style="color:green;" >' + row.name + '</span>';
}
if (row.plan[0].dur < 2) {
cellStyle["cellHTML"] = '<span style="color:black;" >' + row.name + '</span>';
}
}
// Style setting: Person in charge
if (field == "resId") {
if (row.name == "Task Name 1") {
cellStyle["ce11Style"] = 'color:green;font-weight:bold';
}
}
// // Style setting: Custom column (using custom column name)
// if (field == "testCol2") {
// cellStyle["cellHTML"] = '<input id="tstBtn" type ="button" value="Hide milestones" onclick="test1">';
// }
return cellStyle;
});
// Row Rendering Event
myGantt.on("rowRender", function(row, rowStyleObj) {
if (row.isGroup == 1) {
rowStyleObj.rowStyle = 'background:yellow;';
}
return rowStyleObj;
});
// Progress Bar Rendering
myGantt.on("barRender", function (row) {
// Define rendering style object
var barStyle = {};
if (row.name === "Task Name 2") {
barStyle["planBarStyle"] = 'background:red;';
// barStyle["planBarLeftHtml"] = '<img width="20px" height="20px" src="./images/work.svg" />';
// barStyle["planBarOverHtml"] = '';
// barStyle["compBarStyle"] = '';
barStyle["planBarRightHtml"] = '<div style="display:block;">Work hard</div>';
}
// Return object
return barStyle;
});
// Click Progress Bar
myGantt.on("clickBar", function (row, eventXY, dom) {
console.log("click: task" + row.name + ", Click on the date:" + eventXY.date);
});
// Right-click Progress Bar
myGantt.on("rightClick", function (row, eventXY, dom) {
console.log("right click: task:" + row.name + ", Click the object Id:" + dom.id);
console.log("Click on the date:" + eventXY.date);
});
Multiple Loading Methods
To improve loading efficiency, the plugin supports multiple loading methods.
Regular Loading
Load and render all tasks at once.
// Create a Gantt chart object and configure it
myGantt.createGantt("GanttChartDIV", "day");
myGantt.config(ganttConfig);
// Bind data
myGantt.bindGanttData(data);
// ※ The above three steps can be simplified to:
myGantt.createGantt("GanttChartDIV", "day", ganttConfig, data);
Data Listening and Rendering Loading
// Configuration Parameters
var ganttConfig = {
loadType: "listenLoad"
};
// Create a Gantt chart object and configure it
myGantt.createGantt("GanttChartDIV", "day");
myGantt.config(ganttConfig);
// Define Gantt Chart Listener
var dataListener = myGantt.listener;
// Set Gantt chart values, automatically drive the plugin, and update the display.
dataListener.rawGanttData = [
{
"id": 1,
"seq": 1000,
"iconColsVal": [],
"name": "Construction period of Unit A",
"rsltStart": "",
"rsltEnd": "",
"rsltDur": 1,
"planBarColor": "#C0EBE8",
"linkTo": "http://",
"isMS": 0,
"resId": "1",
"pctComp": 0,
"isGroup": 1,
"parentId": "",
"isExpand": 1,
"preNodes": "",
"caption": "Key focus",
"plan": [{ "start": "2023-07-05", "end": "2023-07-06", "dur": 10 }]
}
];
// No need to execute bindGanttData and drawGantt methods
Paginated Rendering
Load all data at once and render it page by page.
// Configuration Parameters
var ganttConfig = {
loadType: "loadAllToPage",
pageSize: 20 // Page size for paginated loading
};
// Create a Gantt chart object and configure it
myGantt.createGantt("GanttChartDIV", "day");
myGantt.config(ganttConfig);
// Bind data (data is displayed page by page)
myGantt.bindGanttData(data);
Paginated Loading and Rendering
Load and render a certain number of rows each time, and load and render page by page.
// Paginated loading handling
// The parameter pageNo is the data for the page the plugin is requesting, starting from 1
function loadPageData(pageNode) {
// Return the Gantt chart data for the specified page paramete
...
}
// Configuration Parameters
var ganttConfig = {
loadType: "loadByPage",
pageSize: 20, // Page size for paginated loading
loadDataFunc: loadPageData // Paginated loading handling
};
// Create a Gantt chart object and configure it
myGantt.createGantt("GanttChartDIV", "day");
myGantt.config(ganttConfig);
// Gantt chart rendering
myGantt.drawGantt();
Row Data Model
Data Item Description
The following table format is the MZGantt Gantt chart data row data model. Before binding data to the Gantt chart, data needs to be created in this format. You can bind data in bulk, refer to the bindGanttDate method; or bind single rows, often used in combination with external pop-up boxes.
| Data Item | Type | Description |
|---|---|---|
| id | (Required) String | 编号 |
| name | (Required) String | Name |
| isGroup | (optional) Number(0 or 1) | Whether it is a group task (parent task), determines whether a task can contain subtasks. |
| iconColsVal | (optional) Array | Array of image objects (src, title) |
| resId | (optional) String | Resource ID |
| resName | (optional) String | Resource Name |
| plan | (optional) Array | Plan object, includes start, end, dur, pctComp,barId,progressStyle,barStyle,titleStyle attributes |
| rsltStart | (optional) String Date | Actual start time |
| rsltEnd | (optional) String Date | Actual end time |
| pctComp | (optional) Number | Completion percentage |
| rsltDur | (optional) Number | Actual effort |
| planBarColor | (optional) String | Gantt chart bar color (planned) |
| preNodes | (optional) String/Array | Predecessor nodes |
| parentId | (optional) String | Parent task ID |
| caption | (optional) String | Title |
| isMS | (optional) Number(0 OR 1) | Is milestone |
| Custom column1 | (optional) String | Custom column |
| Custom column2 | (optional) String | Custom column |
| custRsltBars | (optional) Array | Array of segmented progress bars (name, title, start, end, html, style) |
Model Usage Example
// ****************** Reference for pop-up example ******************
// Use a pop-up, and construct the following data when the pop-up is confirmed
var task = {};
task.name = "Test Task 1"; // (required)Task name
task.isGroup = 0; // (optional)Is parent task (group)
task.iconColsVal = [{"src": "./images/test.jpg","title": "",}]; // (optional)Icon column value
task.resId = "01"; // (optional)Responsible person ID
task.resName = "Andy lau"; // (optional)Responsible person name
task.plan = [{"start": "2023-12-20","end": "2023-12-25","dur": 5}]; // (optional)Planned data
task.planBarColor = "#FF0000"; // (optional)Progress bar color
task.rsltStart = "2023-12-20"; // (optional)Actual start
task.rsltEnd = "2023-12-26"; // (optional)Actual end
task.pctComp = 90; // (optional)Completion percentage
task.rsltDur = 6; // (optional)Completion amount
task.preNodes = [{"id":13,"type":"FS","gapDays":1}]; // (optional)Predecessor tasks (multiple allowed)
task.parentId = ""; // (Optional when saveType is 'add', 'append', or 'insert'; required when saveType is 'addChild') Set the parent task ID here
task.caption = "Test Task 1"; // (optional)Task title
task.isMS = 0; // (optional) Is milestone task
// Update task row data
var ret = MZGantt.updRows(saveType, task); // saveType: add/append/insert/edit/addChild
if (ret.code == 0) {
// Close task input box
} else {
// Display error message
console.log(ret.msg);
return;
}
Advanced Features
MZGantt supports more advanced features such as internationalization and multi-language package settings, dragging to establish and edit task relationships, loading animation configuration, and more.
Internationalization and Language Package Settings
// Set language package
// Note: Set the language type before executing the Gantt chart display method (drawGantt).
myGantt.setGanttLang("en"); // cn: Chinese; en: English; jp: Japanese;
// Character renaming (the following characters can be renamed)
// count_tab: "No",
// reserve_pic: "Reserver",
// theme: "Theme",
// loading:"Loading...",
// click_2_view:"Click to view",
// column_task: "Task Name",
// column_complete_ratio: "Completion percentage",
// column_rslt: "Actual Start-End Date",
// column_start_date: "Planned Start Date",
// column_end_date: "Planned End Date",
// column_rslt_start_date: "Actual Start Date",
// column_rslt_end_date: "Actual End Date",
// week: "Week",
// quarter: "Quarter",
// menu_goto:"Go to Task",
// menu_goto_today:"Go to Today",
// select_child:"Select All Subtasks",
// menu_FF: "Finish-Finish(FF)",
// menu_FS: "Finish-Start(FS)",
// menu_SF: "Start-Finish(SF)",
// menu_SS: "Start-Start (SS)"
var labelDefs = {
"menu_SF":"Start-Finish(SF)"}
;
// Internationalization Settings
myGantt.setMyLabels(labelDefs, "en");
Customizing Progress Bar Tooltips
When you hover over the progress bar, a tooltip will automatically display showing task information. You can also customize the tooltip according to your needs.
// etting Parameters infoBoxItems and infoBoxStyle in Gantt Chart Configuration
var ganttConfig = {
...
infoBoxItems: [ // Infobox item definition
{
title: '',value: "name",
titleStyle: "font-weight: bold;",
valStyle: "font-weight: bold;"},
{
title: 'Formula writing', expression: "((testCol1 * testCol3) + pctComp) + 'Day'",
titleStyle: "font-weight: bold;",
valStyle: "color: red;"},
{
title: 'This is formatting:', value: "This is formatting: {planStart}",
titleStyle: "font-weight: bold;",
valStyle: "color: red;"},
{
title: 'Planned start', value: "planStart",
titleStyle: ""},
{
title: 'Planned end', value: "planEnd",
titleStyle: "", },
{
title: 'Actual start', value: "rsltStart",
titleStyle: ""},
{
title: 'Actual end', value: "rsltEnd",
titleStyle: "", },
{
title: 'Title', value: "title",
titleStyle: "", }
],
infoBoxStyle: // Infobox item style definition
"BORDER: #cdcdcd 1px solid;background:#FFFFFF;box-shadow: 3px 3px 2px #CDCDCD;border-radius:5px;padding:5px;",
...
}
You can choose any of the following methods to configure information items:
1. Use value(vulue)
2. Use formula(expression)
* For date/character type values: Quotes must be added, for example:
> expression: "This is the actual start date: 'rsltStart'"
* Numeric values: Can be directly written in the formula, for example:
> expression: "((testCol1 * testCol3) + pctComp) + 'days'"
3. Use character replacemen {...})
Task Relationships
Establishing Task Relationships: In edit mode, click and drag the mouse downwards on the progress bar of Task A to Task B. Release the mouse, a task relationship dialog box will appear. Select the task relationship, click OK to establish the relationship between Task A and B.
Editing Task Relationships: In edit mode, click the relationship line to open the task relationship dialog box. Modify or delete the task relationship.
Methods for modifying lag time: Method 1: Modify and save in the relationship dialog box. Method 2: Automatically modify by dragging subsequent tasks.
Loading Animation Settings
MZGantt supports displaying loading animations. There are two types: plugin initialization loading animation and manual toggle animation. Please refer to the following examples.
// 1. Plugin initialization animation**************************************************
// 1.1 普通js版本时
<!-- 导入甘特图插件 -->
<link rel="stylesheet" type="text/css" href="../../gantt/mzgantt.css" />
<script language="javascript">
// 参数:show: 是否显示插件初始化动画,默认不显示;containerId:显示到甘特图容器dom对象id,默认整个窗口
window.showInitLoading = {show:true, containerId: "GanttChartDIV"};
</script>
<script language="javascript" src="../../gantt/mzgantt.js"></script>
...
// 1.2 npm版本时
// 初始化甘特图插件(参数解释同上)
var showInitLoadingMsg = {show:true, containerId: "GanttChartDIV"};
const myGantt = MZGantt.init(showInitLoadingMsg);
...
// 2. 手动开关动画****************************************************
// 手动开关打开加载动画时,普通js版本和npm版本使用相同方法。
// 参数1:显示开关(true:显示;false:关闭)
// 参数2:显示位置dom对象ID(默认整个窗口)
myGantt.showLoading(true,"GanttChartDIV");
Methods and Events
MZGantt provides a rich interface to manipulate or control Gantt chart data and features.
nitialization of Instance
Methods |
Description |
Parameters |
|---|---|---|
| init | Initialize Gantt Chart Instance | None (Required when using the plugin in Vue, this method needs to be executed to instantiate the plugin) |
| createGantt | Create Gantt Chart Object | Parameter 1: (Required) DIV container ID Parameter 2: (Optional) Time scale day/week/month/quarter (default is day) Parameter 3: Configuration options Parameter 4: (Optional) Data |
| config | Configure Gantt Chart | JSON object values, refer to: Gantt chart parameter configuration |
| bindGanttData | Bind Gantt Chart Data | Gantt chart JSON data: must comply with the MZGantt data model |
| drawGantt | Display Gantt Chart | None |
display control
Method |
Description |
Parameters |
|---|---|---|
| changeFormat | Change display scale | Display scale:day/week/month/quarter |
| switchTrack | Switch display of actual progress | Toggle value:true/false |
| showMileStone | Toggle display of milestone time markers | Toggle value:true/false |
| setMSLine | Add/modify milestone time marker lines | Milestone definition object (refer to object definition in mileStoneLines) |
| rmMSLine | Remove milestone time marker line | Milestone marker line name |
| showCriticalPath | Toggle display of critical pat | Toggle value:"1"/"0" |
| setRowReadonly | Set row readonly condition | Condition judgment function。 For example, if you set a newly added line to read-only, the code is as follows: myGantt.setRowReadonly(function(row) {return row.operatioin != "new" && row.operatioin != "newmodified";}); |
| adjustGanttHeight | Dynamically adjusts the height of the Gantt chart area, enabling adaptive height for the Gantt chart. | Gantt chart area height (in pixels) |
| setColsVisible | Dynamically sets column visibility. | Refer to the example for parameters, setting colname1 and colname2 as invisible:myGantt.setColsVisible({colname1: false, colname2: false}) |
| fitGanttWidth | Dynamically adjusts the width of the right-side time scale in the Gantt chart, ensuring it perfectly fills the progress bar area. | None |
| fitMobile | Makes the Gantt chart mobile-friendly (automatically switches to landscape orientation). | None |
| hideGanttBar | Hide or Show the Gantt Bar Area on the Right | Toggle value:true/false |
Data Retrieval
Method |
Description |
Parameters |
|---|---|---|
| getAllRows | Gets all row data. | None |
| getUpdatedRows | Gets rows with changed values. | None |
| getSelectedRows | Gets currently selected rows. | None |
| getAllParentRows | Gets all parent tasks. | None |
| getChildRows | Gets all child task data for a specified row. | Task ID |
| getSelectedRowID | Gets the selected row's task ID. | None |
| getSelectedBucketID | Gets the selected bucket ID (used in resource management). | None |
| getSelectedRowSeq | Gets the index number of the currently selected row. | None |
| getSelectedRowParent | Gets the parent task ID of the selected row. | None |
| getMileStoneLines | Gets milestone timeline data. | None |
Property Settings
Method |
Description |
Parameters |
|---|---|---|
| setBulkMoveType | Sets the bulk move type. | D (related tasks) P (by responsible person) N (all subsequent tasks) |
| setStartEndDate | Sets the project start and end dates. | Parameter 1: Start date Parameter 2: End date. String type |
| setToDate | Set Gantt chart to display a specified date | Parameter1: specified Date. Type is string. Parameter2: whether auto-fit the width(true/false) Example: myGantt.setToDate('2025-04-16', true); |
| setGanttStatus | Sets the Gantt chart editing status. | Parameter: Status character (r: read-only; e: editable) . String type |
| setColEditable | Dynamically sets columns as editable or read-only. | Parameter: Key-value object (column name: true/false). Example: { 'planStart': false, 'planEnd': false } true: editable; false: read-only |
Data Editing
Method |
Description |
Parameters |
|---|---|---|
| addRow | Adds a new row. | Parameter: Insertion position add: after the current row; insert: before the current row; append: at the end; addChild: add a child task |
| deleteRows | Deletes selected rows. | None |
| cloneRows | Clones rows. | None |
| updRows | Saves rows. | Parameter 1: Insertion position add: after the current row; insert: before the current row; append: at the end; addChild: add a child task; edit: edit Parameter 2: Task model data Note: When editing inline, the edited data can be obtained directly, so there is no need to use this interface command. When using an external task editing dialog, you can use this interface. |
Filters
Method |
Description |
|---|---|
| addFilter | Sets a condition to filter data. Example:MZGantt.filterRows((task) => {return task.duration > 3;}, "onlyShow") |
| removeFilter | Removes the filter and restores data display. Example:MZGantt.removeFilter() |
Export as Image
Method |
Description |
Parameters |
|---|---|---|
| exportGanttImg | Save as an image | None |
Event Listening
Event Name |
Description |
|---|---|
| cellRender | Cell render event. Supports listening to this event and setting custom callback handling. Renders cells. Example: MZGantt.on("cellRender", function(row, cellObj) {...}) |
| cellBlur | Cell blur event. Triggered when a cell loses focus during inline editing. Example:MZGantt.on("cellBlur", function(row, cellName, oldVal, newVal) {...}) |
| rowRender | Row render event. Supports listening to this event and setting custom callback handling. Renders row styles. Example: MZGantt.on("rowRender", function(row, rowStyleObj) {...}) |
| barRender | Bar render event. Can dynamically listen to user data and render bar styles in real time. Example: MZGantt.on("barRender", function(row, barObj) {...}) |
| clickBar | Bar click event. Example: MZGantt.on("clickBar", function(row, eventXY, dom) {...}) |
| dblClickBar | Bar dbl-click event。 Example: MZGantt.on("dblClickBar", function(row, barData, dom) {...}) |
| clickRow | Row click event。 Example: MZGantt.on("clickRow", function(row, eventXY) {...}) |
| rightClickBar | Gantt bar right-click event. Example: MZGantt.on("rightClick", function(row, eventXY, dom) {...}) |
loaded | Loading complete event. Automatically executed after the Gantt chart is loaded. You can set your own processing logic as needed. Example: MZGantt.on("loaded", function(e, data) {...}) |
| barDragEnd | Bar drag end event. Triggered when you release a dragged bar. Example:MZGantt.on("barDragEnd", function(row, updRows) {...}) |
| rowDragEnd | Row drag end event. Triggered when you release a dragged row。Example: MZGantt.on("rowDragEnd", function(row, updRows) {...}) |
Common Error Codes
Error Code |
Description |
|---|---|
| 0x00010 | The createGantt command must be executed after the Gantt chart container div has been fully loaded, otherwise this error is displayed. |
| 0x00020 | Error configuring the Gantt chart. |
| 0x00030 | Error rendering the Gantt chart (drawGantt command). |
| 0x00040 | Error rendering milestone markers. |
| 0x00050 | Data binding exception. Please refer to <Section 4. Gantt Chart Data Row Data Model> for creating Gantt chart row data. |
| 0x00060 | Exception loading task data in bulk. |
| 0x00080 | Error occurred when clicking on a cell. |
| 0x00090 | Error occurred when clicking on a progress bar. |
| 0x00100 | Plugin initialization exception. |