Cytoscape.js changing style of node on click

class, click, cytoscape.js, selection

Solution

I think of the classes as like css classes. When you first initialised cytoscape you can have an optional `style` parameter like ...

var cy = cytoscape({
  style: [
   {
    selector: '.myFirstClass',
    style: {
    'background-color': 'red',
    'shape': 'rectangle'
    ...
   },
   {
    selector: '.mySecondClass',
    style: {
    'background-color': 'blue',
    'shape': 'triangle'
    ...
   }
});

Now when you change the style of a node it will reflect what you set in the stylesheet. So...

`cy.$('#nodeA').classes('mySecondClass');`, where `#nodeA` is the id of your node. This will turn your first node into a blue triangle.

Hope that helped.

Problem

I cannot seem to be able to change the style of a node on click. I need to do this programatically to keep track of two nodes in the graph, basically to have two nodes 'selected' at same time, with each being a different type I define. There are examples such at the one here (http://js.cytoscape.org/#eles.addClass) that 'drops' a new style in the sheet for certain nodes. I don't understand how these classes work, where they are defined in the stylesheet and on what event they can be used. The docs for the library does not provide an actual explanation of classes, where to define them and what they can be used for. Any help is much appreciated.

Original source