Search code examples
javascriptcytoscape.jscytoscape

cytoscape.js how to display nodes in div?


I have been trying around with my code for a while but i only get an empty div displayed and i dont know why.

         var elementsStr = "[";
         for(var i = 0;i < elements.length; i++) {
             var toConCat = "{data:{id:\"node-" + i + "\"}},";
             elementsStr = elementsStr.concat(toConCat);
             if(isEven(i) && i != 0) {
                 console.log(i);
                 toConCat = "{data: {id:\"edge-" + i/2 + "\",source:\"node-" + i-1 + "\",target:\"node-" + i + "\"}},";
                 elementsStr = elementsStr.concat(toConCat);
             }

         }
         var toConCat = "{data:{id:\"edge-" + (elements.length/2) + "\",source:\"node-" + (elements.length-2) + "\",target:\"node-" + (elements.length-1) + "\"}}";
         elementsStr = elementsStr.concat(toConCat);
         elementsStr = elementsStr.concat("]");
         console.log(elementsStr);
        responseDiv.innerHTML = "";
         var cy = cytoscape({
             container: responseDiv,

             style: [
                {
                    selector: 'node',
                    style: {
                        'background-color': '#666',
                        'label': 'data(id)'
                    }   
                },
                {
                    selector: 'edge',
                    style: {
                        'width': 3,
                        'line-color': '#ccc',
                        'target-arrow-color': '#ccc',
                        'target-arrow-shape': 'triangle'
                    }
                }
            ],
            layout: {
                name: 'grid',
                rows: 1
            }

         });
        var eles = cy.add(elementsStr);
        console.log(eles);
     }
 };

elementsStr is

[{data:{id:"node-0"}},{data:{id:"node-1"}},{data:{id:"edge-1",source:"node-0",target:"node-1"}}]

in the end, but nothing is displayed, what am i doing wrong?


Solution

  • That approach is quite complicated, just stick to the documentation on cy.add() and try building the elements not as a string concatination but like a json file, also, maybe use single quotes for the id:

    var nodes = [];
    for (var i = 0; i < elements.length; i++)
        nodes.push({ group: "nodes", data: { id: i });
    }
    var k = 0;
    for (var i = 0; i < elements.length; i+=2)
        nodes.push({ group: "edges", data: { id: "e" + k, source: "n" + i, target: "n" + (i + 1) } });
        k += 1;
    }
    cy.add(nodes);
    

    In your html file, just add a div with the right id, don't touch it after that, I don't really know why you added the .innerHtml = "", thats not necessary:)