Scroll the gantt to a given position on first load

Hi

When the gantt chart is loaded, it is always scrolled to the left. I would like to shift it to ‘today’ (or to the right, when today is in the future) - but only when the gantt is loaded for the first time. I went through many similar topics on the forum, but nothing worked reliably so far. My code looks like this:

gantt.init("gantt_here");
gantt.load(`/gantt/api/v1/data?key=${userApiToken}`);

const state = gantt.getState();
const today = new Date();
let position;

if (state.max_date.getTime() <= today.getTime()) {
    let end_date = gantt.date.add(state.max_date, -1, "day");
    position = gantt.posFromDate(end_date);
    gantt.scrollTo(position, null);
} else if (state.min_date.getTime() <  today.getTime() && today.getTime() < state.max_date.getTime()) {
    position = gantt.posFromDate(today);
    let offset = (gantt.$container.offsetWidth - gantt.config.grid_width) / 3;
    gantt.scrollTo(position - offset, null);
}

This code doesn’t work unfortunately. I also tried to put the ‘scrolling’ code to a function, which was called after various events had been triggered. I tried ‘onDataRender’, ‘onGanttRender’, also on first ‘onGanttRender’ after ‘onParse’ etc. Nothing worked. Eventually I put this code into a setTimeout function i.e.

setTimeout({
       // scrollTo....
}, 500);

And it worked. This proved my suspicion that the code is always called prematurely, before loading of gantt is finished and that’s why it doesn’t work. However this is hardly a reliable solution. In case of a large amount of data, or some network problems, it won’t work anyway and longer timeout means that user has to wait whether it is necessary or not. On the other hand I was not able to find a solution using one of the events the gantt chart provides to call the code when the gantt is fully loaded. The problem with these events is, that they are called more than once and if I don’t want to call this code later (for any other rendering or loading), I’m not able to identify the right moment when to call this code.

The question is - is there a reliable way how to scroll the gantt after it is loaded for the first time only?

Thank you very much for your help

Ondrej

Hello Ondrej,
You can use the onLoadEnd event handler and use a variable to scroll the chart only once:
https://docs.dhtmlx.com/gantt/api__gantt_onloadend_event.html
If you don’t want to show the first task after the data is loaded (in other words, don’t scroll to it), you need to disable the gantt.config.initial_scroll parameter:
https://docs.dhtmlx.com/gantt/api__gantt_initial_scroll_config.html

Here is an example of how it can be implemented:
http://snippet.dhtmlx.com/5/9059a65c5

Thank you for your answer Ramil, I’ll try it. Maybe the problem was in the gantt.config.initial_scroll setting - I wasn’t aware of that.

Ondrej