Get task index on "onAfterTaskAdd" event


I’m trying to get the index of a task created on onAfterTaskAdd event, but I get undefined or -1 using “$index” property or using gantt.getGlobalTaskIndex.

const onAfterTaskAdd = gantt.attachEvent("onAfterTaskAdd", (id, item) => {
  const tG = gantt.getTask(id)
  var index = tG["$index"]

  console.log(tG.$index) // undefined
  console.log(gantt.getGlobalTaskIndex(id)) //-1
  console.log(index) //undefined


So, how can I get the index of a newly created task?

Thanks in advance

Hi @aibarr!

I’m not sure I understand you correctly, but I’ve tried to reproduce your issue in this snippet. Please open it and click on the + and Add new task buttons. Look at the messages in the top right with hte indexes of created tasks:

What version of Gantt do you use?

Please, reproduce the issue in the snippet:
Then click on the “share” button and send me the link.

Hi @guldmi

I was able to partialy replicate the problem on the next Snippet

As you can see, when “$index” is called an “undefined” is obtained. This time, gantt.getGlobalTaskIndex throws right, but I think that it does because it wins on race conditions. My code on the “onAfterTaskAdd” event is actually more longer than this example, so in the console of my code it actually keeps evaluating while the event execution doesn’t finished yet; this is just an assumption, so I’m not plenty sure about this.

Thanks for all!

The $index parameter is undefined because although the task is added, it is not displayed in the chart. The gantt.getGlobalTaskIndex(id) command calculates the index.
You can see how it works in the following snippet:
gantt.getTaskRowNode returns the div element of the task row in the grid. That element appears only after the data is rendered on the page.