I have a requirement. When opening the Gantt chart for the first time, the line will be displayed in the middle of the Gantt today. How to achieve this? I need your help

I have a requirement. When opening the Gantt chart for the first time, the line will be displayed in the middle of the Gantt today. How to achieve this? I need your help。
like this

Hello,
To scroll to the specific date, you need to use the showDate method:
https://docs.dhtmlx.com/gantt/api__gantt_showdate.html

With that method, Gantt will change the scroll position and add some offset, so that the date won’t be displayed at the left part of the viewport. But it won’t be the centered position.

So, you need to use a different approach.
First, you need to get the position of the date. You can do that with the posFromDate method:
https://docs.dhtmlx.com/gantt/api__gantt_posfromdate.html

Then you will need to get the width of the viewport and divide it by 2:

gantt.$task.offsetWidth

After that, you can subtract that value from the date position. So, if you scroll to that position, the target date will appear in the center.

You can scroll to the specific position in the timeline by using the scrollTo method:
https://docs.dhtmlx.com/gantt/api__gantt_scrollto.html

Here is an example of how it can be implemented:

Also, if the target date is outside the displayed date range, you need to extend it by specifying both the gantt.config.start_date and gantt.config.end_date properties:
https://docs.dhtmlx.com/gantt/api__gantt_start_date_config.html

Then you need to repaint the changes with the render method and call the function that will scroll to the target date.

I should invoke scrollTo at which event or time point? I tried adding this action in the onGanttRender event, but it didn’t scroll to the expected position when the page was first opened. However, after refreshing the page, it scrolled to the expected position.

Hello,
You can add that code after the gantt.parse or gantt.load methods, and Gantt will scroll to the specified date after the tasks are loaded.

If you call the code in the onGanttRender event handler, it will be called each time Gantt needs to repaint its structure (for example, when you collapse/expand a task).

Also, if you attach the onGanttRender event after the tasks are loaded, it will be called only after Gantt needs to repaint its structure. If you attach it before Gantt is initialized, it will be called several times: during the initialization and loading the data.

1 Like