cytoscape.jscytoscapecytoscape-web

Dynamically add a css class to cytoscape node on the tap of the node using cytoscape.js


I am trying to add class on the tap of the node in cytoscape.js. Here is the link for the complete code:

https://stackblitz.com/edit/angular-kpnys1?file=src%2Fapp%2Fapp.component.ts

ngViewAfterInit function

  cy.on("tap", "node", function(evt) {
      var node = evt.target;
      console.log("tapped " + node.id());
      cy.nodes(node).classes("foo");
    });

Tap works fine but it does not add any class to the node. Is that possible?


Solution

  • You'll have to use the correct method for that. Currently, your code calls node.classes(), which deletes all previous classes of the node (you basically overwrite the classes array of a node).

    What you want to do: Use node.addClass("foo") and add an entry in your stylesheet:

    {
        selector: ".foo",
        css: {
            "background-color": "green"
        }
    }
    

    The dot indicates a class, but you can specify even further. If you want to add the foo class only to parent nodes, change .foo to :parent.foo.

    But aside that, your code acutally worked (kind of), the class was present when clicking on a node. Here is the edited version of your stackblitz, I added the mentioned changes and gave one parent element the class "bar". If you click on a parent, the node will change the background-color to green and log its current classes to the console:

    stackblitz