cy.fit() does not work immediately, it needs timeout to fit the graph. Cytoscape js

Viewed 304

So after initializing the graph, I want to make it fit to its div by using cy.fit(). I have done this:

var cy = cytoscape({
        container: document.getElementById("cy"),
        elements: {
            nodes: nodes,
            edges: edges
        },
        layout: {
            name: 'dagre',
            
        },
          
        style: [
            {
              selector: 'node',
              css: { 
                'label': 'data(id)',
                'background-color': '#808080'
             }
 
          ]
      });
     

So after this part if I do

cy.fit()

It does not work. But if I do this:

setTimeout(() => { 
        cy.fit();
    },1000); 

It works. However first the unfitted graph gets displayed and then after 1000 ms the proper graph fit gets displayed. Thus When a page is loaded, it looks like the graph is written twice.

How can I fix this? Is there a way to initialize the graph with this 'fit' option? Or any other way to fix it?

Thank you

1 Answers

Cytoscape.js deals with this via cy.ready(). Just use it like this:

var cy = cytoscape({
  container: document.getElementById("cy"),
  elements: {
    nodes: nodes,
    edges: edges
  },
  layout: {
    name: 'dagre',
  },
  style: [{
    selector: 'node',
    css: {
      'label': 'data(id)',
      'background-color': '#808080'
    }
  }]
});

cy.ready(function() {
  cy.fit();
});

Also, you can just use the layout option fit for this:

layout: { name: 'dagre', fit: true }
Related