Styling options based on conditions for a cytoscape.js visualization

I am looking to modify the appearance of my graph based on JavaScript variables that are globally set. For example, if my edges contain attributes such as name and price, I want to customize the labels of the edges depending on a global variable called label_type:

let label_type = 'I_want_name_labels'
switch(label_type) {
  case 'I_want_name_labels':
    cy.style().selector('edge').style({'label': 'data(name)'});
    break;
  case 'I_want_price_labels':
    cy.style().selector('edge').style({'label': 'data(price)'});
    break;
}

The code above is not working as expected (no labels displayed), and I'm unsure why. Here is the structure of my edges:

{
  "data": {
    "id": "node_node2",
    "source": "node1",
    "target": "node2",
    "directed": true,
    "name": "Baltazar",
    "price": 1095.73
  }
}

Note: I attempted to use

cy.filter('edge').style({'label': 'data(name)'})
instead, but it seems that accessing data this way raises a warning:

The style property `label: data(name)` is invalid

So, how can I implement conditional styling in cytoscape.js? What am I missing here?

Answer №1

Check out this specific line:

// Use .data() to access all properties of the target element, for example, use .id() to directly get the id of the element
targetElement.style('label', targetElement.data('faveColor'));

Below is a demo showing how you can initialize and modify the labels of nodes/edges:

var cy = (window.cy = cytoscape({
  container: document.getElementById("cy"),

  boxSelectionEnabled: false,
  autounselectify: true,

  style: [{
      selector: "node",
      css: {
        "label": "data(id)",
        "text-valign": "center",
        "text-halign": "center",
        "height": "60px",
        "width": "100px",
        "shape": "rectangle",
        "background-color": "data(faveColor)"
      }
    },
    {
      selector: "edge",
      css: {
        "curve-style": "bezier",
        "control-point-step-size": 40,
        "target-arrow-shape": "triangle"
      }
    }
  ],

  elements: {
    nodes: [{
        data: {
          id: "Top",
          faveColor: "#2763c4",
          wants: "id"
        }
      },
      {
        data: {
          id: "yes",
          faveColor: "#37a32d",
          wants: "id"
        }
      },
      {
        data: {
          id: "no",
          faveColor: "#2763c4",
          wants: "id"
        }
      },
      {
        data: {
          id: "Third",
          faveColor: "#2763c4",
          wants: "color"
        }
      },
      {
        data: {
          id: "Fourth",
          faveColor: "#56a9f7",
          wants: "color"
        }
      }
    ],
    edges: [{
        data: {
          source: "Top",
          target: "yes"
        }
      },
      {
        data: {
          source: "Top",
          target: "no"
        }
      },
      {
        data: {
          source: "no",
          target: "Third"
        }
      },
      {
        data: {
          source: "Third",
          target: "Fourth"
        }
      },
      {
        data: {
          source: "Fourth",
          target: "Third"
        }
      }
    ]
  },
  layout: {
    name: "dagre"
  }
}));

cy.bind('click', 'node, edge', function(event) {
  cy.nodes().each(function(ele, i, eles) {
    ele.style('label', (ele.data('wants') == 'id') ? ele.data('id') : ele.data('faveColor'));
  });
});
body {
  font: 14px helvetica neue, helvetica, arial, sans-serif;
}

#cy {
  height: 85%;
  width: 100%;
  float: right;
  position: absolute;
}
<html>

<head>
  <meta charset=utf-8 />
  <meta name="viewport" content="user-scalable=no, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, minimal-ui">
  <script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="98fbe1ecf7ebfbf9e8fdd8abb6abb6a8">[email protected]</a>/dist/cytoscape.min.js">
  </script>
  <!-- cyposcape dagre -->
  <script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="debabfb9acbb9eeef0e9f0ea">[email protected]</a>/dist/dagre.js"></script>
  <script src="https://cdn.rawgit.com/cytoscape/cytoscape.js-dagre/1.5.0/cytoscape-dagre.js"></script>
</head>

<body>
  <div id="cy"></div>
</body>

</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Look up HTML div tags and showcase the findings on a separate webpage

I am looking to search through multiple HTML files from a different page. I want to find text within all the divs that have a specific id, and display those divs on the search results page if they contain the matched search term. Here is an example of how ...

Leverage ConvexGeometry within the npm release of THREE

Is there a way to utilize ConvexGeometry in the npm version of THREE? It appears that it was introduced in r85: https://github.com/mrdoob/three.js/releases I noticed that it's only present in the example folder. Is there a method to incorporate it ...

Which alternative function can I use instead of onchange without having to modify the slider beforehand in order for it to function properly?

Check out my website: alainbruno.nl/form.html to see the "Race" form and the "Age" slider. I've noticed that the minimum and maximum values of the Age slider only update correctly when you first use the slider before selecting a different race. Any id ...

Using React.js CSSTransition Component properties with TransitionGroup

Exploring ways to animate a group of divs has led me to discover this example which perfectly fits my needs. However, as I am still new to React, I'm having trouble understanding how the props are passed through the <Fade> component, specificall ...

Implementing OAuth2 in a Microservices architecture to establish a user account

In my current setup, I am utilizing a React Application along with a separate Express API. My goal is to allow users to register through my React app. To do this, I believe the oauth2 flows should follow these steps: Prompt the user for information (suc ...

The DOM HTMLElement's className property is empty when the element does not have a class name specified

What is the value of the HTMLElement className property when it has no class name set in HTML? Initially, I thought it would be undefined, but I discovered that in Firefox, it is actually an empty string. This raises the question - can this behavior be r ...

Groups containing nested conditionals

Currently, I have been analyzing data in the following format: ID Count Report Rank X-01 1 4.2 2 X-01 2 2.7 1 X-01 3 5.8 3 X-01 4 14 5 X-01 5 9.2 4 X-02 1 6.8 2 X-02 2 ...

Does the first Ajax call always finish first in the order of Ajax calls?

In my code, I have an ajax call that triggers another ajax call based on its return value. The URL parameter of the second call is modified by the output of the first one. These two calls are interrelated as the first call feeds the URL parameter for the s ...

Execute the controller function once all asynchronous calls to the Angular service have finished

I have integrated the Angular Bootstrap Calendar using a custom cell template and cell modifier. Within my controller, I need to retrieve configuration data from a service that is required by the cellModifier function before it is executed. (function() { ...

Using the `after()` method in jQuery, you can append an additional element after the

I am facing a challenge where I need to dynamically add multiple tr elements using the after() function to a tr variable in jQuery and then return the entire element. However, when I try to return the tr variable, it only includes the original tr without t ...

Conceal a div containing a specific class during the page's loading process, then reveal it once the

Is there a way to hide a specific div class while a page is loading? Here is the structure I am working with: <div id ="container"> <div class="project-item tv"></div> <div class="project-item radio"></div> <div class="pro ...

What is the process for including a field specific to a date in a form?

I need the user to select a month and year. In one column, there will be the days of the month they selected [e.g. 1-30]. Users can then add habits in other columns. I want users to be able to input an 'X' for each habit row on a specific date [e ...

React Native application crashes on Android 12 and above when run on an emulator

Currently in the process of creating a music application named Wavelet. Listed below are my dependencies: package.json Typically, I debug on an Android 11 emulator; however, when switching to an Android 12 emulator or using my physical device running on A ...

Leveraging jQuery to dynamically load an icon based on the content within a <label> tag

I manage a website that dynamically fetches content from a database, with varying contents for each label. For example, one label may be generated as General:, while another may be generated as TV:. My question is, can jQuery be used to replace the text NA ...

Is my approach to gradually unveiling a 3D object in Three.js correct?

I'm eager to craft a dynamic 3D line chart using three.js that emerges from left to right, similar to the demonstration on CNBC found here: http://youtu.be/ds7zhCqlrqk?t=12s Initially, I explored options like hiding, masking, or clipping segments of ...

AJAX request: No values are being returned by $_GET

After spending hours trying to figure this out... I've been working on using AJAX to grab values from a jQuery slider within an <input> tag. The AJAX request is not failing (see code below), and when I use console.log to check the variable I&ap ...

Leveraging viewbag information in combination with jQuery JSON techniques

I have a desire to utilize my ViewBag within a JavaScript array. After researching on using viewbag with jquery asp.net mvc 3, I believe I found the code that suits my needs: @model MyViewModel <script type="text/javascript"> var model = @Html. ...

Guide to comparing two TSX elements in a React + TSX environment

I am facing difficulties in comparing two React TSX elements. Despite being new to both React and TSX, I have tried copying and pasting the exact elements for comparison but it doesn't seem to work. Can you guide me on what might be causing this issue ...

Exploring depths with recursive div search in JavaScript

Given a specific id of a div element on my webpage, I am looking to recursively search through all its children until I locate a div with a particular text string as its content, at which point I want to remove that element... function removeWhereTextIs(t ...

The error message "TypeError: res.json is not a function in express.router" indicates that

I encountered the following error message and I'm not sure how to resolve it: TypeError: res.json is not a function I have reviewed the express documentation but couldn't find any syntax errors or issues. Here is my code: index.js import expr ...