Graph theory (network) library for visualisation and analysis

Demos

Introduction

Factsheet

About

Cytoscape.js is an open-source graph theory (a.k.a. network) library written in JS. You can use Cytoscape.js for graph analysis and visualisation.

Cytoscape.js allows you to easily display and manipulate rich, interactive graphs. Because Cytoscape.js allows the user to interact with the graph and the library allows the client to hook into user events, Cytoscape.js is easily integrated into your app, especially since Cytoscape.js supports both desktop browsers, like Chrome, and mobile browsers, like on the iPad. Cytoscape.js includes all the gestures you would expect out-of-the-box, including pinch-to-zoom, box selection, panning, et cetera.

Cytoscape.js also has graph analysis in mind: The library contains many useful functions in graph theory. You can use Cytoscape.js headlessly on Node.js to do graph analysis in the terminal or on a web server.

Cytoscape.js is an open-source project, and anyone is free to contribute. For more information, refer to the GitHub README.

The library was created at the Donnelly Centre at the University of Toronto. It is the successor of Cytoscape Web.

Packages

npm : npm install cytoscape

bower : bower install cytoscape

jspm : jspm install npm:cytoscape

Releases

Citation

To cite Cytoscape.js in a paper, please cite the Oxford Bioinformatics issue:

Cytoscape.js: a graph theory library for visualisation and analysis

Franz M, Lopes CT, Huck G, Dong Y, Sumer O, Bader GD

Bioinformatics (2016) 32 (2): 309-311 first published online September 28, 2015 doi:10.1093/bioinformatics/btv557 (PDF)

PubMed abstract

Funding

Funding for Cytoscape.js and Cytoscape is provided by NRNB (U.S. National Institutes of Health, National Center for Research Resources grant numbers P41 RR031228 and GM103504) and by NIH grants 2R01GM070743 and 1U41HG006623. The following organizations help develop Cytoscape:

ISB | UCSD | MSKCC | Pasteur | Agilent | UCSF | Unilever | Toronto | NCIBI | NRNB

Notation

Graph model

Cytoscape.js supports many different graph theory usecases. It supports directed graphs, undirected graphs, mixed graphs, loops, multigraphs, compound graphs (a type of hypergraph), and so on.

We are regularly making additions and enhancements to the library, and we gladly accept feature requests and pull requests.

Architecture & API

There are two components in the architecture that a programmer must be concerned with in order to use Cytoscape.js, the core (i.e. a graph instance) and the collection. In Cytoscape.js, the core is a programmer’s main entry point into the library. From the core, a programmer can run layouts, alter the viewport, and perform other operations on the graph as a whole.

The core provides several functions to access elements in the graph. Each of these functions returns a collection, a set of elements in the graph. Functions are available on collections that allow the programmer to filter the collection, perform operations on the collection, traverse the graph about the collection, get data about elements in the collection, and so on.

Note that a collection is immutable by default, meaning that the set of elements within a collection can not be changed. The API returns a new collection with different elements when necessary, instead of mutating the existing collection. This allows the programmer to safely use set theory operations on collections, use collections functionally, and so on. Note that because a collection is just a list of elements, it is relatively inexpensive to create new collections.

For very performance intensive code, a collection can be treated as mutable with eles.merge() and eles.unmerge() . Most apps should never need these functions.

Functions

There are several types that different functions can be executed on, and the variable names used to denote these types in the documentation are outlined below:

Shorthand Works on cy the core eles a collection of one or more elements (nodes and edges) ele a collection of a single element (node or edge) nodes a collection of one or more nodes node a collection of a single node edges a collection of one or more edges edge a collection of a single edge layout a layout ani an animation

By default, a function returns a reference back to the calling object to allow for chaining (e.g. obj.fn1().fn2().fn3() ). Unless otherwise indicated in this documentation, a function is chainable in this manner unless a different return value is specified. This applies both to the core and to collections.

For functions that return a value, note that calling a singular — ele , node , or edge — function on a collection of more than one element will return the expected value for only the first element.

Object ownership

When passing objects to Cytoscape.js for creating elements, animations, layouts, etc., the objects are considered owned by Cytoscape. Objects like elements have several levels to them, and doing deep copies of those objects every time they are passed to Cytoscape creates additional expense. When desired, the programmer can copy objects manually before passing them to Cytoscape. However, copying is not necessary for most programmers most of the time.

Gestures

Cytoscape.js supports several gestures:

Grab and drag background to pan : touch & desktop

Pinch to zoom : touch & desktop (with supported trackpad)

Mouse wheel to zoom : desktop

Two finger trackpad up or down to zoom : desktop

Tap to select : touch & desktop

Tap background to unselect : desktop

Taphold background to unselect : desktop & touch

Multiple selection via modifier key (shift, command, control, alt) + tap : desktop

Box selection : touch (three finger swipe) & desktop (modifier key + mousedown then drag)

Grab and drag nodes : touch & desktop

All gesture actions can be controlled by the programmer, toggling them on or off whenever needed.

Position

A node’s position refers to the centre point of its body.

There is an important distinction to make for position: A position may be a model position or a rendered position.

A model position — as its name suggests — is the position stored in the model for an element. An element’s model position remains constant, despite changes to zoom and pan. Numeric style property values are specified in model co-ordinates, e.g. a node with width 20px will be 20 pixels wide at zoom 1.

A rendered position is an on-screen location relative to the viewport. For example, a rendered position of { x: 100, y: 100 } specifies a point 100 pixels to the right and 100 pixels down from the top-left corner of the viewport. The model position and rendered position are the same at zoom 1 and pan (0, 0).

An element’s rendered position naturally changes as zoom and pan changes, because the element’s on-screen position in the viewport changes as zooming and panning are applied. Panning is always measured in rendered coordinates.

In this documentation, “position” refers to model position unless otherwise stated.

A node’s position can be set manually, or it can be set automatically using a layout. Because the positions of two nodes influence the lengths of the edges in between them, a layout effectively sets edge lengths.

Elements JSON

Examples are given that outline format of the elements JSON used to load elements into Cytoscape.js:

cytoscape({ container : document .getElementById( 'cy' ), elements : [ { group : 'nodes' , data : { id : 'n1' , parent : 'nparent' , }, scratch : { _foo : 'bar' }, position : { x : 100 , y : 100 }, selected : false , selectable : true , locked : false , grabbable : true , pannable : false , classes : [ 'foo' , 'bar' ] }, { data : { id : 'n2' }, renderedPosition : { x : 200 , y : 200 } }, { data : { id : 'n3' , parent : 'nparent' }, position : { x : 123 , y : 234 } }, { data : { id : 'nparent' } }, { data : { id : 'e1' , source : 'n1' , target : 'n2' }, pannable : true } ], layout : { name : 'preset' }, style : [ { selector : 'node' , style : { 'label' : 'data(id)' } } ] });

The elements JSON may alternatively be in the following format, keyed by group:

cytoscape({ container : document .getElementById( 'cy' ), elements : { nodes : [ { data : { id : 'a' } }, { data : { id : 'b' } } ], edges : [ { data : { id : 'ab' , source : 'a' , target : 'b' } } ] }, layout : { name : 'grid' , rows : 1 }, style : [ { selector : 'node' , style : { 'label' : 'data(id)' } } ] });

Compound nodes

Compound nodes are an addition to the traditional graph model. A compound node contains a number of child nodes, similar to how a HTML DOM element can contain a number of child elements.

Compound nodes are specified via the parent field in an element’s data . Similar to the source and target fields of edges, the parent field is normally immutable: A node’s parent can be specified when the node is added to the graph, and after that point, this parent-child relationship is immutable via ele.data() . However, you can move child nodes via eles.move() .

A compound parent node does not have independent dimensions (position and size), as those values are automatically inferred by the positions and dimensions of the descendant nodes.

As far as the API is concerned, compound nodes are treated just like regular nodes — except in explicitly compound functions like node.parent() . This means that traditional graph theory functions like eles.dijkstra() and eles.neighborhood() do not make special allowances for compound nodes, so you may need to make different calls to the API depending on your usecase.

For instance:

var a = cy.$( '#a' ); var directlyConnected = a.neighborhood(); var indirectlyConnected = a.add( a.descendants() ).neighborhood();

Getting started

This section will familiarise you with the basic steps necessary to start using Cytoscape.js.

Including Cytoscape.js

If you are using a simple HTML environment (without a build system), then source Cytoscape.js in a <script> tag or import it as an ES6 module, e.g.:

< script src = "cytoscape.min.js" > </ script >

or

< script type = "module" > import cytoscape from "./cytoscape.esm.min.js" ; </ script >

To use Cytoscape.js from a CDN, use one of the following CDNs:

Please do not hotlink to copies of Cytoscape.js from the documentation — they’re just for the demos.

The available files are available under cytoscape/dist/ in the npm package:

cytoscape.min.js : A minified UMD build with all dependencies included in the bundle. This file is useful for small pages, supplementary material for an academic paper for example.

: A minified UMD build with all dependencies included in the bundle. This file is useful for small pages, supplementary material for an academic paper for example. cytoscape.umd.js : A non-minified UMD build with all dependencies included in the bundle. This file is useful for debugging on small pages, supplementary material for an academic paper for example.

: A non-minified UMD build with all dependencies included in the bundle. This file is useful for debugging on small pages, supplementary material for an academic paper for example. cytoscape.esm.min.js : A minified ESM ( import / export ) build with all dependencies included in the bundle. This file serves the same purpose as the above, but it can be imported as an ES6 module without the need for a bundler.

: A minified ESM ( / ) build with all dependencies included in the bundle. This file serves the same purpose as the above, but it can be imported as an ES6 module without the need for a bundler. cytoscape.cjs.js : A non-minified CJS (Node.js) build without any bundled dependencies. This is intended to be consumed automatically by Node.js or a bundler like Webpack via require('cytoscape') .

: A non-minified CJS (Node.js) build without any bundled dependencies. This is intended to be consumed automatically by Node.js or a bundler like Webpack via . cytoscape.esm.js : A non-minified ESM ( import / export ) build without any bundled dependencies. This is intended to be consumed automatically by Node.js or a bundler like Webpack via import cytoscape from 'cytoscape' .

Note that Cytoscape.js uses the dimensions of your HTML DOM element container for layouts and rendering at initialisation. Thus, it is very important to place your CSS stylesheets in the <head> before any Cytoscape.js-related code. Otherwise, dimensions may be sporadically reported incorrectly, resulting in undesired behaviour.

Your stylesheet may include something like this (assuming a DOM element with ID cy is used as the container):

#cy { width : 300px ; height : 300px ; display : block; }

To install Cytoscape.js via npm:

npm install cytoscape

To use Cytoscape.js in a ESM environment with npm (e.g. Webpack or Node.js with the esm package):

import cytoscape from 'cytoscape' ;

To use Cytoscape.js in a CommonJS environment like Node.js:

var cytoscape = require ( 'cytoscape' );

To use Cytoscape.js with AMD/Require.js:

require ([ 'cytoscape' ], function ( cytoscape ) { });

To install Cytoscape.js via Bower:

bower install cytoscape

To install Cytoscape.js via Meteor/Atmosphere:

npm install cytoscape

Cytoscape.js supports environments with ES5 or newer, as it is transpiled by Babel and it uses only basic features of the standard library. Feature detection is used for optional features that improve performance. However, a future version of Cytoscape.js may require a more up-to-date version of the standard library. You may want to use babel-polyfill or core-js if you want to support old browsers in future.

Initialisation

An instance of Cytoscape.js corresponds to a graph. You can create an instance as follows:

var cy = cytoscape({ container : document .getElementById( 'cy' ) });

You can pass a jQuery instance as the container for convenience:

var cy = cytoscape({ container : $( '#cy' ) });

If you are running Cytoscape.js in Node.js or otherwise running it headlessly, you will not specify the container option. In implicitly headless environments like Node.js, an instance is automatically headless. To explicitly run a headless instance (e.g. in the browser) you can specify options.headless as true .

Specifying basic options

For visualisation, the container , elements , style , and layout options usually should be set:

var cy = cytoscape({ container : document .getElementById( 'cy' ), elements : [ { data : { id : 'a' } }, { data : { id : 'b' } }, { data : { id : 'ab' , source : 'a' , target : 'b' } } ], 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' , 'curve-style' : 'bezier' } } ], layout : { name : 'grid' , rows : 1 } });

Next steps

Now that you have a core (graph) instance with basic options, explore the core API. It’s your entry point to all the features in Cytoscape.js.

If you have code questions about Cytoscape.js, please feel free to post your question to Stackoverflow.

Core

The core object is your interface to a graph. It is your entry point to Cytoscape.js: All of the library’s features are accessed through this object.

Initialisation

Initialisation

A graph can be created as follows:

var cy = cytoscape({ });

You can initialise the core without any options. If you want to use Cytoscape as a visualisation, then a container DOM element is required, e.g.:

var cy = cytoscape({ container : document .getElementById( 'cy' ) });

Note that in order to guarantee custom font usage (WOFF/WOFF2), the fonts in question must be loaded before Cytoscape is initialised.

Note that Cytoscape.js will print warning messages to the console to help programmers avoid mistakes. If you want to disable these messages, call cytoscape.warnings(false) to turn warnings off completely. You can turn them back on with cytoscape.warnings(true) , and you can get the current state with cytoscape.warnings() . It is recommended that you leave warnings enabled at least for development builds of your app.

The following sections go over the options in more detail.

Initialisation options

An instance of Cytoscape.js has a number of options that can be set on initialisation. They are outlined below with their default values.

Note that everything is optional. By default, you get an empty graph with the default stylesheet. Environments outside the browser (e.g. Node.js) are automatically set as headless for convenience.

var cy = cytoscape({ // very commonly used options container: undefined, elements: [ /* ... */ ], style: [ /* ... */ ], layout: { name: 'grid' /* , ... */ }, // initial viewport state: zoom: 1, pan: { x: 0, y: 0 }, // interaction options: minZoom: 1e-50, maxZoom: 1e50, zoomingEnabled: true, userZoomingEnabled: true, panningEnabled: true, userPanningEnabled: true, boxSelectionEnabled: true, selectionType: 'single', touchTapThreshold: 8, desktopTapThreshold: 4, autolock: false, autoungrabify: false, autounselectify: false, // rendering options: headless: false, styleEnabled: true, hideEdgesOnViewport: false, textureOnViewport: false, motionBlur: false, motionBlurOpacity: 0.2, wheelSensitivity: 1, pixelRatio: 'auto' });

Very commonly used options

container : A HTML DOM element in which the graph should be rendered. This is unspecified if Cytoscape.js is run headlessly. The container is expected to be an empty div; the visualisation owns the div.

elements : An array of elements specified as plain objects. For convenience, this option can alternatively be specified as a promise that resolves to the elements JSON.

style : The stylesheet used to style the graph. For convenience, this option can alternatively be specified as a promise that resolves to the stylesheet.

layout : A plain object that specifies layout options. Which layout is initially run is specified by the name field. Refer to a layout’s documentation for the options it supports. If you want to specify your node positions yourself in your elements JSON, you can use the preset layout — by default it does not set any positions, leaving your nodes in their current positions (i.e. specified in options.elements at initialisation time).

Initial viewport state

zoom : The initial zoom level of the graph. Make sure to disable viewport manipulation options, such as fit , in your layout so that it is not overridden when the layout is applied. You can set options.minZoom and options.maxZoom to set restrictions on the zoom level.

pan : The initial panning position of the graph. Make sure to disable viewport manipulation options, such as fit , in your layout so that it is not overridden when the layout is applied.

Interaction options

minZoom : A minimum bound on the zoom level of the graph. The viewport can not be scaled smaller than this zoom level.

maxZoom : A maximum bound on the zoom level of the graph. The viewport can not be scaled larger than this zoom level.

zoomingEnabled : Whether zooming the graph is enabled, both by user events and programmatically.

userZoomingEnabled : Whether user events (e.g. mouse wheel, pinch-to-zoom) are allowed to zoom the graph. Programmatic changes to zoom are unaffected by this option.

panningEnabled : Whether panning the graph is enabled, both by user events and programmatically.

userPanningEnabled : Whether user events (e.g. dragging the graph background) are allowed to pan the graph. Programmatic changes to pan are unaffected by this option.

boxSelectionEnabled : Whether box selection (i.e. drag a box overlay around, and release it to select) is enabled. If enabled while panning is also enabled, the user must use a modifier key (shift, alt, control, or command) to use box selection.

selectionType : A string indicating the selection behaviour from user input. For 'additive' , a new selection made by the user adds to the set of currently selected elements. For 'single' , a new selection made by the user becomes the entire set of currently selected elements (i.e. the previous elements are unselected).

touchTapThreshold & desktopTapThreshold : A non-negative integer that indicates the maximum allowable distance that a user may move during a tap gesture, on touch devices and desktop devices respectively. This makes tapping easier for users. These values have sane defaults, so it is not advised to change these options unless you have very good reason for doing so. Large values will almost certainly have undesirable consequences.

autoungrabify : Whether nodes should be ungrabified (not grabbable by user) by default (if true , overrides individual node state).

autolock : Whether nodes should be locked (not draggable at all) by default (if true , overrides individual node state).

autounselectify : Whether nodes should be unselectified (immutable selection state) by default (if true , overrides individual element state).

Rendering options

headless : A convenience option that initialises the instance to run headlessly. You do not need to set this in environments that are implicitly headless (e.g. Node.js). However, it is handy to set headless: true if you want a headless instance in a browser.

styleEnabled : A boolean that indicates whether styling should be used. For headless (i.e. outside the browser) environments, display is not necessary and so neither is styling necessary — thereby speeding up your code. You can manually enable styling in headless environments if you require it for a special case. Note that it does not make sense to disable style if you plan on rendering the graph. Also note that cy.destroy() must be called to clean up a style-enabled, headless instance.

hideEdgesOnViewport : A rendering hint that when set to true makes the renderer not render edges while the viewport is being manipulated. This makes panning, zooming, dragging, et cetera more responsive for large graphs. This option is now largely moot, as a result of performance enhancements.

textureOnViewport : A rendering hint that when set to true makes the renderer use a texture during panning and zooming instead of drawing the elements, making large graphs more responsive. This option is now largely moot, as a result of performance enhancements.

motionBlur : A rendering hint that when set to true makes the renderer use a motion blur effect to make the transition between frames seem smoother. This can increase the perceived performance for a large graphs. This option is now largely moot, as a result of performance enhancements.

motionBlurOpacity : When motionBlur: true , this value controls the opacity of motion blur frames. Higher values make the motion blur effect more pronounced. This option is now largely moot, as a result of performance enhancements.

wheelSensitivity : Changes the scroll wheel sensitivity when zooming. This is a multiplicative modifier. So, a value between 0 and 1 reduces the sensitivity (zooms slower), and a value greater than 1 increases the sensitivity (zooms faster). This option is set to a sane value that works well for mainstream mice (Apple, Logitech, Microsoft) on Linux, Mac, and Windows. If the default value seems too fast or too slow on your particular system, you may have non-default mouse settings in your OS or a niche mouse. You should not change this value unless your app is meant to work only on specific hardware. Otherwise, you risk making zooming too slow or too fast for most users.

pixelRatio : Overrides the screen pixel ratio with a manually set value ( 1.0 recommended, if set). This can be used to increase performance on high density displays by reducing the effective area that needs to be rendered, though this is much less necessary on more recent browser releases. If you want to use the hardware’s actual pixel ratio, you can set pixelRatio: 'auto' (default).

Graph manipulation

cy.add() Add elements to the graph and return them. cy.add( , eleObj ) Add a specified element to the graph. eleObj A plain object that specifies the element. cy.add( , eleObjs ) Add the specified elements to the graph. eleObjs An array of elements specified by plain objects. cy.add( , eles ) Add the specified elements to the graph. eles A collection of elements. Details If plain element objects are used, then the same format used at initialisation must be followed. If a collection of existing elements is specified to a different core instance, then copies of those elements are added, which allows for elements to be effectively transferred between instances of Cytoscape.js. Examples Add a node from a plain object. cy.add({ group : 'nodes' , data : { weight : 75 }, position : { x : 200 , y : 200 } }); Add nodes and edges to the graph as plain objects: var eles = cy.add([ { group : 'nodes' , data : { id : 'n0' }, position : { x : 100 , y : 100 } }, { group : 'nodes' , data : { id : 'n1' }, position : { x : 200 , y : 200 } }, { group : 'edges' , data : { id : 'e0' , source : 'n0' , target : 'n1' } } ]);

cy.remove() Remove elements from the graph and return them. cy.remove( , eles ) Remove the specified elements. eles A collection of elements to remove. cy.remove( , selector ) Remove elements in the graph matching the specified selector. selector Elements matching this selector are removed. Details Note that removing a node necessarily removes its connected edges. Though the elements specified to this function are removed from the graph, they may still exist in memory. However, almost all functions will not work on removed elements. For example, the eles.neighborhood() function will fail for a removed element: An element outside of the context of the graph can not have a neighbourhood defined. A removed element exists only so you can restore it back to the originating core instance or to a new instance. Examples Remove an element: var j = cy.$( '#j' ); cy.remove( j ); Remove a collection: var collection = cy.elements( 'node[weight > 50]' ); cy.remove( collection ); Remove elements matching a selector: cy.remove( 'node[weight > 50]' );

cy.collection() Return a new, empty collection. cy.collection() Get an empty collection. Details This function is useful for building up collections. Examples Keep a collection of nodes that have been clicked: var collection = cy.collection(); cy.nodes().on( 'click' , function ( e ) { var clickedNode = e.target; collection = collection.union(clickedNode); });

cy.getElementById() Aliases: cy.$id() , Get an element from its ID in a very performant way. cy.getElementById( , id ) id The ID of the element to get. Examples cy.getElementById( 'j' ); Using the shorter alias: cy.$id( 'j' );

cy.$() et al et al Get elements in the graph matching a selector or a filter function. cy.$( , selector ) Get elements in the graph matching the specified selector. selector The selector the elements should match. cy.elements( , selector ) Get elements in the graph matching the specified selector. selector The selector the elements should match. cy.nodes( , selector ) Get nodes in the graph matching the specified selector. selector The selector the nodes should match. cy.edges( , selector ) Get edges in the graph matching the specified selector. selector The selector the edges should match. cy.filter( , selector ) Get elements in the graph matching the specified selector. selector The selector the elements should match. cy.filter( , function(ele, i, eles) ) Get elements in the graph matching the specified filter function. function(ele, i, eles) The filter function that returns true for elements that should be returned. ele The current element under consideration for filtering. i The counter used for iteration over the elements in the graph. eles The collection of elements being filtered

Details If no elements in the graph match the selector, an empty collection is returned. The function cy.$() acts as an alias to cy.filter() : It lets you type less characters. It is analogous to the jQuery $ alias used to search the document Examples Get nodes with weight greater than 50: cy.nodes( '[weight > 50]' ); Get edges with source node n0 : cy.edges( '[source = "j"]' ); Get all nodes and edges with weight greater than 50: cy.elements( '[weight > 50]' ); cy.filter( '[weight > 50]' ); Get nodes with weight greater than 50 with a filter function: cy.filter( function ( element, i ) { return element.isNode() && element.data( 'weight' ) > 50 ; });

cy.batch() et al et al Allow for manipulation of elements without triggering multiple style calculations or multiple redraws. cy.batch( , function() ) function() A callback within which you can make batch updates to elements. cy.startBatch() Starts batching manually (useful for asynchronous cases). cy.endBatch() Ends batching manually (useful for asynchronous cases). Details Do not add batching to your app unless you have identified an applicable performance bottleneck. There are restrictions on what kind of code you can run in a batch. Normally, when you modify elements, each modification can trigger a style calculation and a redraw — depending on timing for a redraw. For example, the following will cause two style calculations and at least one draw: cy.$( '#j' ) .data( 'weight' , '70' ) .addClass( 'funny' ) .removeClass( 'serious' ) ; This is not a problem for a handful of operations on a handful of elements, but for many operations on many elements you end up with redundant style calculations and probably redundant redraws. In the worst case, you have eles.length * numOps style updates and redraws — and both style updates and redraws can be expensive. In the worst case when using cy.batch() , you limit the style updates to eles.length and you limit the redraws to just one. Thus, this function is useful for making many changes to elements at once. When the specified callback function is complete, only elements that require it have their style updated and the renderer makes at most a single redraw. This makes for very efficient modifications to elements, but it has some caveats inside a batch: You can not reliably read element style or dimensions (it may have changed, or computed values may be out of date).

You probably do not want to use eles.style() et cetera because they force a style bypass rather than a recalculation.

et cetera because they force a style bypass rather than a recalculation. You can not apply any style-dependent operation within the batch if you have already modified style within the same batch. Common style-dependent operations include: Layout: cy.layout() , eles.layout() , etc. Reading style: ele.style() , ele.numericStyle() , etc. Reading dimensions: ele.midpoint() , ele.boundingBox() , etc. Animation: ele.animation() , cy.animate() , etc. And so on…

A batch should correspond to a single visual operation. Usually a batch should contain calls only to the following functions: Modifying state: eles.data() , eles.scratch() , eles.addClass() , eles.removeClass() , etc.

, , , , etc. Building collections: eles.union() , eles.difference() , eles.intersection() , etc.

, , , etc. Comparison: eles.same() , eles.some() , etc.

, , etc. Iteration: eles.forEach() , eles.empty() , etc.

, , etc. Traversal: node.outgoers() , eles.bfs() , etc.

, , etc. Algorithms: eles.dijkstra() , eles.degreeCentrality() , etc. Examples Synchronous style: cy.batch( function ( ) { cy.$( '#j' ) .data( 'weight' , '70' ) .addClass( 'funny' ) .removeClass( 'serious' ) ; }); Asynchronous style: cy.startBatch(); cy.$( '#j' ) .data( 'weight' , '70' ) .addClass( 'funny' ) .removeClass( 'serious' ) ; cy.endBatch();

cy.mount() Attaches the instance to the specified container for visualisation. cy.mount( , container ) container A HTML DOM element in which the graph should be rendered. Details If the core instance is headless prior to calling cy.mount() , then the instance will no longer be headless and the visualisation will be shown in the specified container. If the core instance is non-headless prior to calling cy.mount() , then the visualisation is swapped from the prior container to the specified container.

cy.unmount() Remove the instance from its current container. Details This function sets the instance to be headless after unmounting from the current container.

cy.destroy() A convenience function to explicitly destroy the instance. Details The cy.destroy() function is not necessary but can be convenient in some cases. It cleans up references and rendering loops such that the memory used by an instance can be garbage collected. If you remove the container DOM element from the page, then the instance is cleaned up automatically. Similarly, calling cy.destroy() does this cleanup and removes all the container’s children from the page. When running Cytoscape.js headlessly, using cy.destroy() is necessary only if you’ve explicitly enabled style functionality. To drop the memory used by an instance, it is necessary to drop all of your own references to that instance so it can be garbage collected.

cy.destroyed() Get whether the instance of Cytoscape.js has been destroyed or not.

Data

cy.data() Aliases: cy.attr() , Read and write developer-defined data associated with the graph. cy.data() Get the entire data object. cy.data( , name ) Get a particular data field. name The name of the field to get. cy.data( , name , value ) Set a particular data field. name The name of the field to set.

value The value to set for the field. cy.data( , obj ) Update multiple data fields at once via an object. obj The object containing name-value pairs to update data fields.

cy.removeData() Aliases: cy.removeAttr() , Remove developer-defined data associated with the elements. cy.removeData() Removes all mutable data fields for the elements. cy.removeData( , names ) Removes the specified mutable data fields for the elements. names A space-separated list of fields to delete.

cy.scratch() Extension function: This function is intended for use in extensions. Set or get scratchpad data, where temporary or non-JSON data can be stored. App-level scratchpad data should use namespaces prefixed with underscore, like '_foo' . This is analogous to the more common ele.scratch() but for graph global data. cy.scratch() Get the entire scratchpad object for the core. cy.scratch( , namespace ) Get the scratchpad at a particular namespace. namespace A namespace string. cy.scratch( , namespace , value ) Set the scratchpad at a particular namespace. namespace A namespace string.

value The value to set at the specified namespace.

cy.removeScratch() Extension function: This function is intended for use in extensions. Remove scratchpad data. You should remove scratchpad data only at your own namespaces. This is analogous to the more common ele.removeScratch() but for graph global data. cy.removeScratch( , namespace ) Remove the scratchpad data at a particular namespace. namespace A namespace string. Note that ele.removeScratch() sets the scratchpad object for the specified namespace to undefined . This allows you to use meaningful null values.

Events

cy.on() Aliases: cy.bind() , cy.listen() , cy.addListener() , Listen to events that occur on the core. cy.on( , events [ , selector] , function(event) ) events A space separated list of event names.

selector [optional] A selector to specify elements for which the handler runs.

function(event) The handler function that is called when one of the specified events occurs. event The event object.

Examples Listen to events that bubble up from elements matching the specified node selector: cy.on( 'tap' , 'node' , function ( evt ) { var node = evt.target; console .log( 'tapped ' + node.id() ); }); Listen to all tap events that the core receives: cy.on( 'tap' , function ( event ) { var evtTarget = event.target; if ( evtTarget === cy ){ console .log( 'tap on background' ); } else { console .log( 'tap on some element' ); } });

cy.promiseOn() Aliases: cy.pon() , Get a promise that is resolved when the core emits the first of any of the specified events. cy.promiseOn( , events [ , selector] ) events A space separated list of event names.

selector [optional] A selector to specify elements for which the handler runs. Examples cy.pon( 'tap' ).then( function ( event ) { console .log( 'tap promise fulfilled' ); });

cy.one() Listen to events that occur on the core, and run the handler only once. cy.one( , events [ , selector] , function(event) ) events A space separated list of event names.

selector [optional] A selector to specify elements for which the handler runs.

function(event) The handler function that is called when one of the specified events occurs. event The event object.

Examples cy.one( 'tap' , 'node' , function ( ) { console .log( 'tap!' ); }); cy.$( 'node' ).eq( 0 ).trigger( 'tap' ); cy.$( 'node' ).eq( 1 ).trigger( 'tap' );

cy.removeListener() Aliases: cy.off() , cy.unbind() , cy.unlisten() , Remove event handlers on the core. cy.removeListener( , events [ , selector] [ , handler] ) events A space separated list of event names.

selector [optional] The same selector used to listen to the events.

handler [optional] A reference to the handler function to remove. Examples For all handlers: cy.on( 'tap' , function ( ) { }); cy.removeListener( 'tap' ); For a particular handler: var handler = function ( ) { console .log( 'called handler' ); }; cy.on( 'tap' , handler); var otherHandler = function ( ) { console .log( 'called other handler' ); }; cy.on( 'tap' , otherHandler); cy.removeListener( 'tap' , handler);

cy.removeAllListeners() Remove all event handlers on the core.

cy.emit() Aliases: cy.trigger() , Emit one or more events. cy.emit( , events [ , extraParams] ) events A list of event names to emit (either a space-separated string or an array)

extraParams [optional] An array of additional parameters to pass to the handler. Examples cy.on( 'tap' , function ( evt, f, b ) { console .log( 'tap' , f, b); }); cy.emit( 'tap' , [ 'foo' , 'bar' ]);

cy.ready() Run a callback as soon as the graph becomes ready (i.e. intitial data loaded and initial layout completed). If the graph is already ready, then the callback is called immediately. If data is loaded synchronously and the layout used is discrete/synchronous/unanimated/unspecified, then you don't need cy.ready() . cy.ready( , function(event) ) function(event) The callback run as soon as the graph is ready. event The ready event.



Viewport manipulation

cy.container() Get the HTML DOM element in which the graph is visualised. A null value is returned if the instance is headless.

cy.center() Aliases: cy.centre() , Pan the graph to the centre of a collection. cy.center() Centre on all elements in the graph. cy.center( , eles ) Centre on the specified elements. eles The collection to centre upon. Details If no collection is specified, then the graph is centred on all nodes and edges in the graph. Examples Centre the graph on node j : var j = cy.$( '#j' ); cy.center( j );

cy.fit() Pan and zooms the graph to fit to a collection. cy.fit() Fit to all elements in the graph. cy.fit( [ , eles] [ , padding] ) Fit to the specified elements. eles [optional] The collection to fit to.

padding [optional] An amount of padding (in rendered pixels) to have around the graph (default 0 ). Details If no collection is specified, then the graph is fit to all nodes and edges in the graph. Examples Fit the graph on nodes j and e : cy.fit( cy.$( '#j, #e' ) );

cy.reset() Reset the graph to the default zoom level and panning position. cy.reset() Resets the zoom and pan. Details This resets the viewport to the origin (0, 0) at zoom level 1. Examples set Timeout ( function( ){ cy.pan({ x : 50 , y : -100 }); }, 1000 ); set Timeout ( function( ){ cy.zoom( 2 ); }, 2000 ); set Timeout ( function( ){ cy.reset(); }, 3000 );

cy.pan() Get or set the panning position of the graph. cy.pan() Get the current panning position. cy.pan( , renderedPosition ) Set the current panning position. renderedPosition The rendered position to pan the graph to. Details This function pans the graph viewport origin to the specified rendered pixel position. Examples Pan the graph to (100, 100) rendered pixels. cy.pan({ x : 100 , y : 100 }); console .log( cy.pan() );

cy.panBy() Relatively pan the graph by a specified rendered position vector. cy.panBy( , renderedPosition ) renderedPosition The rendered position vector to pan the graph by. Details This function shifts the viewport relatively by the specified position in rendered pixels. That is, specifying a shift of 100 to the right means a translation of 100 on-screen pixels to the right. Examples Pan the graph 100 pixels to the right. cy.panBy({ x : 100 , y : 0 });

cy.panningEnabled() Get or set whether panning is enabled. cy.panningEnabled() Get whether panning is enabled. cy.panningEnabled( , bool ) Set whether panning is enabled. bool A truthy value enables panning; a falsey value disables it. Examples Enable: cy.panningEnabled( true ); Disable: cy.panningEnabled( false );

cy.userPanningEnabled() Get or set whether panning by user events (e.g. dragging the graph background) is enabled. cy.userPanningEnabled() Get whether user panning is enabled. cy.userPanningEnabled( , bool ) Set whether user panning is enabled. bool A truthy value enables user panning; a falsey value disables it. Examples Enable: cy.userPanningEnabled( true ); Disable: cy.userPanningEnabled( false );

cy.zoom() Get or set the zoom level of the graph. cy.zoom() Get the zoom level. cy.zoom( , level ) Set the zoom level. level The zoom level to set. cy.zoom( , options ) Set the zoom level. options The options for zooming. level The zoom level to set. position The position about which to zoom. renderedPosition The rendered position about which to zoom.

Details The zoom level must be a positive number. Zoom levels that are not numbers are ignored; zoom levels that are numbers but outside of the range of valid zoom levels are considered to be the closest, valid zoom level. When zooming about a point via cy.zoom( options ) , the options are defined as follows. For zooming about a rendered position (i.e. a position on-screen): cy.zoom({ level : 2.0 , renderedPosition : { x : 100 , y : 100 } }); For zooming about a model position: cy.zoom({ level : 2.0 , position : { x : 0 , y : 0 } }); You can zoom about a position or a rendered position but not both. You should specify only one of options.position or options.renderedPosition . Examples Zoom in to factor 2 cy.zoom( 2 ); Zoom in to the minimum zoom factor cy.zoom( 0 ); Zoom in to the maximum zoom factor cy.zoom( 1 / 0 ); Zoom about a node cy.zoom({ level : 1.5 , position : cy.getElementById( 'j' ).position() });

cy.zoomingEnabled() Get or set whether zooming is enabled. cy.zoomingEnabled() Get whether zooming is enabled. cy.zoomingEnabled( , bool ) Set whether zooming is enabled. bool A truthy value enables zooming; a falsey value disables it. Examples Enable: cy.zoomingEnabled( true ); Disable: cy.zoomingEnabled( false );

cy.userZoomingEnabled() Get or set whether zooming by user events (e.g. mouse wheel, pinch-to-zoom) is enabled. cy.userZoomingEnabled() Get whether user zooming is enabled. cy.userZoomingEnabled( , bool ) Set whether user zooming is enabled. bool A truthy value enables user zooming; a falsey value disables it. Examples Enable: cy.userZoomingEnabled( true ); Disable: cy.userZoomingEnabled( false );

cy.minZoom() Get or set the minimum zoom level. cy.minZoom() Get the minimum zoom level. cy.minZoom( , zoom ) Set the minimum zoom level. zoom The new minimum zoom level to use.

cy.maxZoom() Get or set the maximum zoom level. cy.maxZoom() Get the maximum zoom level. cy.maxZoom( , zoom ) Set the maximum zoom level. zoom The new maximum zoom level to use.

cy.viewport() Set the viewport state (pan & zoom) in one call. cy.viewport( , zoom , pan ) zoom The zoom level to set.

pan The pan to set (a rendered position). Examples cy.viewport({ zoom : 2 , pan : { x : 100 , y : 100 } });

cy.boxSelectionEnabled() Get or set whether box selection is enabled. If enabled along with panning, the user must hold down one of shift, control, alt, or command to initiate box selection. cy.boxSelectionEnabled() Get whether box selection is enabled. cy.boxSelectionEnabled( , bool ) Set whether box selection is enabled. bool A truthy value enables box selection; a falsey value disables it. Examples Enable: cy.boxSelectionEnabled( true ); Disable: cy.boxSelectionEnabled( false );

cy.selectionType() Get or set the selection type. The 'single' selection type is the default, tapping an element selects that element and deselects the previous elements. The 'additive' selection type toggles the selection state of an element when tapped. cy.selectionType() Get the selection type string. cy.selectionType( , type ) Set the selection type. type The selection type string; one of 'single' (default) or 'additive' .

cy.width() Get the on-screen width of the viewport in pixels.

cy.height() Get the on-screen height of the viewport in pixels.

cy.extent() Get the extent of the viewport, a bounding box in model co-ordinates that lets you know what model positions are visible in the viewport. Details This function returns a plain object bounding box with format { x1, y1, x2, y2, w, h } .

cy.autolock() Get or set whether nodes are automatically locked (i.e. if true , nodes are locked despite their individual state). cy.autolock() Get whether autolocking is enabled. cy.autolock( , bool ) Set whether autolocking is enabled. bool A truthy value enables autolocking; a falsey value disables it. Examples Enable: cy.autolock( true ); Disable: cy.autolock( false );

cy.autoungrabify() Get or set whether nodes are automatically ungrabified (i.e. if true , nodes are ungrabbale despite their individual state). cy.autoungrabify() Get whether autoungrabifying is enabled. cy.autoungrabify( , bool ) Set whether autoungrabifying is enabled. bool A truthy value enables autoungrabbifying; a falsey value disables it. Examples Enable: cy.autoungrabify( true ); Disable: cy.autoungrabify( false );

cy.autounselectify() Get or set whether nodes are automatically unselectified (i.e. if true , nodes are unselectable despite their individual state). cy.autounselectify() Get whether autounselectifying is enabled. cy.autounselectify( , bool ) Set whether autounselectifying is enabled. bool A truthy value enables autounselectifying; a falsey value disables it. Examples Enable: cy.autounselectify( true ); Disable: cy.autounselectify( false );

cy.resize() Aliases: , Force the renderer to recalculate the viewport bounds. Details If your code resizes the graph’s dimensions or position (i.e. by changing the style of the HTML DOM element that holds the graph, or by changing the DOM element’s position in the DOM tree), you will want to call cy.resize() to have the graph resize and redraw itself. If tapping in the graph is offset rather than at the correct position, then a call to cy.resize() is necessary. Tapping can also become offset if the container element is not empty; the container is expected to be empty so the visualisation can use it. Cytoscape.js can not automatically monitor the bounding box of the viewport, as querying the DOM for those dimensions can be expensive. Although cy.resize() is automatically called for you on the window ‘s resize event, there is no resize or style event for arbitrary DOM elements.

Animation

cy.animated() Get whether the viewport is currently being animated.

cy.animate() Animate the viewport. cy.animate( , options ) options An object containing the details of the animation. zoom A zoom level (number) or a zoom configuration object to which the graph will be animated. level The zoom level to use. position The position about which zooming occurs. This automatically modifies the pan such that the specified model position remains at the same position in the viewport extent during zooming. renderedPosition The rendered position about which zooming occurs, as an alternative to using the model position. This automatically modifies the pan such that the model position, corresponding to the rendered position at the start of the animation, remains at the same position in the viewport extent during zooming. pan A panning position to which the graph will be animated. panBy A relative panning position to which the graph will be animated. fit An object containing fitting options from which the graph will be animated. eles Elements or a selector to which the viewport will be fitted. padding Padding to use with the fitting (default 0 ). center An object containing centring options from which the graph will be animated. eles Elements or a selector to which the viewport will be centred. duration The duration of the animation in milliseconds. queue A boolean indicating whether to queue the animation (default true ). Queued animations on the core run in order until the queue is empty. easing A transition-timing-function easing style string that shapes the animation progress curve. complete A function to call when the animation is done. step A function to call each time the animation steps.

Examples Manual pan and zoom: cy.animate({ pan : { x : 100 , y : 100 }, zoom : 2 }, { duration : 1000 }); Fit to elements: var j = cy.$( '#j' ); cy.animate({ fit : { eles : j, padding : 20 } }, { duration : 1000 });

cy.animation() Get an animation of the viewport. cy.animation( , options ) options An object containing the details of the animation. zoom A zoom level (number) or a zoom configuration object to which the graph will be animated. level The zoom level to use. position The position about which zooming occurs. This automatically modifies the pan such that the specified model position remains at the same position in the viewport extent during zooming. renderedPosition The rendered position about which zooming occurs, as an alternative to using the model position. This automatically modifies the pan such that the model position, corresponding to the rendered position at the start of the animation, remains at the same position in the viewport extent during zooming. pan A panning position to which the graph will be animated. panBy A relative panning position to which the graph will be animated. fit An object containing fitting options from which the graph will be animated. eles Elements or a selector to which the viewport will be fitted. padding Padding to use with the fitting (default 0 ). center An object containing centring options from which the graph will be animated. eles Elements or a selector to which the viewport will be centred. duration The duration of the animation in milliseconds. easing A transition-timing-function easing style string that shapes the animation progress curve. complete A function to call when the animation is done. step A function to call each time the animation steps.



cy.delay() Add a delay between queued animations for the viewport. cy.delay( , duration , complete ) duration How long the delay should be in milliseconds.

complete A function to call when the delay is complete. Examples cy .animate({ fit : { eles : '#j' } }) .delay( 1000 ) .animate({ fit : { eles : '#e' } }) ;

cy.delayAnimation() Get a delay animation of the viewport. cy.delayAnimation( , duration ) duration How long the delay should be in milliseconds.

cy.stop() Stop all viewport animations that are currently running. cy.stop( , clearQueue , jumpToEnd ) clearQueue A boolean (default false ), indicating whether the queue of animations should be emptied.

jumpToEnd A boolean (default false ), indicating whether the currently-running animations should jump to their ends rather than just stopping midway. Examples cy.animate({ fit : { eles : '#j' } }, { duration : 2000 }); set Timeout ( function( ){ cy.stop(); }, 1000 );

cy.clearQueue() Remove all queued animations for the viewport.

Layout

cy.layout() Aliases: cy.createLayout() , cy.makeLayout() , Get a new layout, which can be used to algorithmically position the nodes in the graph. cy.layout( , options ) options The layout options. You must specify options.name with the name of the layout you wish to use. This function creates and returns a layout object. You may want to keep a reference to the layout for more advanced usecases, such as running multiple layouts simultaneously. Note that you must call layout.run() in order for it to affect the graph. The layout includes all elements in the graph at the moment cy.layout() is called, as cy.layout() is equivalent to cy.elements().layout() . You can use eles.layout() to run a layout on a subset of the elements in the graph. Examples var layout = cy.layout({ name : 'random' }); layout.run();

Style

cy.style() Get the entry point to modify the visual style of the graph after initialisation. cy.style() Get the current style object. cy.style( , stylesheet ) Assign a new stylesheet to replace the existing one. stylesheet Either a cytoscape.stylesheet() object, a string stylesheet, or a JSON stylesheet (the same formats accepted for options.style at initialisation). Details You can use this function to gain access to the visual style (stylesheet) after initialisation. This is useful if you need to change the entire stylesheet at runtime. Set a new style by reference: var stringStylesheet = 'node { background-color: cyan; }' ; cy.style( stringStylesheet ); Set an entirely new style to the graph, specifying selectors and style properties via function calls: cy.style() .resetToDefault() .selector( 'node' ) .style( 'background-color' , 'magenta' ) .update() ; Set a completely new stylesheet (without the default stylesheet as a base): cy.style() .clear() .selector( 'node' ) .style( 'background-color' , 'magenta' ) .selector( 'edge' ) .style({ 'width' : 3 , 'line-color' : 'yellow' }) .update() ; Add to the existing stylesheet: cy.style() .selector( 'node' ) .style({ 'background-color' : 'yellow' }) .update() ; Set the style from plain JSON: cy.style() .fromJson([ { selector : 'node' , style : { 'background-color' : 'red' } } ]) .update() ; Set the style from a style string (that you would probably pull from a file on your server): cy.style() .fromString( 'node { background-color: blue; }' ) .update() ; Get the current style as JSON: var styleJson = cy.style().json(); var serializedJson = JSON .stringify( styleJson );

Export

cy.png() Export the current graph view as a PNG image. cy.png( , options ) options The export options. output Whether the output should be 'base64uri' (default), 'base64' , 'blob' , or 'blob-promise' (a promise that resolves to the blob is returned). bg The background colour of the image (transparent by default). full Whether to export the current viewport view ( false , default) or the entire graph ( true ). scale This value specifies a positive number that scales the size of the resultant image. maxWidth Specifies the scale automatically in combination with maxHeight such that the resultant image is no wider than maxWidth . maxHeight Specifies the scale automatically in combination with maxWidth such that the resultant image is no taller than maxHeight .

Details This function exports the currently-rendered graph as an image, so you may not call this function on a headless instance. By default, the export takes into account the current screen pixel density so that the image is of the same quality of the screen. If the maxWidth or maxHeight options are specified, then the screen pixel density is ignored so that the image can fit in the specified dimensions. Specifying output:'blob-promise' is the only way to make this function non-blocking. Other outputs may hang the browser until finished, especially for a large image. Examples var png64 = cy.png(); document .querySelector( '#png-eg' ).setAttribute( 'src' , png64); Example image tag:

cy.jpg() Aliases: cy.jpeg() , Export the current graph view as a JPG image. cy.jpg( , options ) options The export options. output Whether the output should be 'base64uri' (default), 'base64' , 'blob' , or 'blob-promise' (a promise that resolves to the blob is returned). bg The background colour of the image (white by default). full Whether to export the current viewport view ( false , default) or the entire graph ( true ). scale This value specifies a positive number that scales the size of the resultant image. maxWidth Specifies the scale automatically in combination with maxHeight such that the resultant image is no wider than maxWidth . maxHeight Specifies the scale automatically in combination with maxWidth such that the resultant image is no taller than maxHeight . quality Specifies the quality of the image from 0 (low quality, low filesize) to 1 (high quality, high filesize). If not set, the browser's default quality value is used.

Details This function exports the currently-rendered graph as an image, so you may not call this function on a headless instance. By default, the export takes into account the current screen pixel density so that the image is of the same quality of the screen. If the maxWidth or maxHeight options are specified, then the screen pixel density is ignored so that the image can fit in the specified dimensions. Specifying output:'blob-promise' is the only way to make this function non-blocking. Other outputs may hang the browser until finished, especially for a large image. The JPEG format is lossy, whereas PNG is not. This means that cy.jpg() is useful for cases where filesize is more important than pixel-perfect images. JPEG compression will make your images (especially edge lines) blurry and distorted. Examples var jpg64 = cy.jpg(); document .querySelector( '#jpg-eg' ).setAttribute( 'src' , jpg64); Example image tag:

cy.json() Import or export the graph in the same JSON format used at initialisation. cy.json( , flatEles ) Export the graph as JSON. flatEles Whether the resulant JSON should include the elements as a flat array ( true ) or as two keyed arrays by group ( false , default). cy.json( , cyJson ) Import the graph as JSON, updating only the fields specified. cyJson The object with the fields corresponding to the states that should be changed. Details This function returns the same object that is used for initialisation. You will find this function useful if you would like to save the entire state of the graph, either for your own purposes or for future restoration of that graph state. This function can also be used to set graph state as in cy.json( cyJson ) , where each field in cyJson is to be mutated in the graph. For each field defined in cyJson , cy is updated to match with the corresponding events emitted. This allows for declarative changes on the graph to be made. For cy.json( cyJson ) , all mutable initialisation options are supported. When setting cy.json({ elements: ... }) the included elements are mutated as specified (i.e. as they would be by ele.json( eleJson ) ),

), the included elements not in the graph are added, and

the not included elements are removed from the graph. When setting cy.json({ style: ... }) the entire stylesheet is replaced, and

the style is recalculated for each element. Updating the stylesheet is expensive. Similarly, it can potentially be expensive to update the existing elements for large graphs — as each element needs to be considered, and potentially each field per element. For elements, a much cheaper option is to selectively call ele.json(...) with only the fields that need to be updated. Examples console .log( cy.json() ); cy.json({ zoom : 2 });

Collection

A collection contains a set of nodes and edges. Calling a function applies the function to all elements in the collection. When reading values from a collection, eles.data() for example, the value of the first element in the collection is returned. For example:

var weight = cy.nodes().data( "weight" ); console .log( cy.nodes()[ 0 ].data( "weight" ) + ' == ' + weight );

You can ensure that you’re reading from the element you want by using a selector to narrow down the collection to one element (i.e. eles.size() === 1 ) or the eles.eq() function.

Also note that collections are iterable for modern browsers which support the iteration protocols. This enables the use of features such as the spread operator, for-of loops, and destructuring.

Graph manipulation

ele.cy() Get the core instance that owns the element.

eles.remove() Remove the elements from the graph, and return all elements removed by this call. Details This function removes the calling elements from the graph. The elements are not deleted — they still exist in memory — but they are no longer in the graph. A removed element just exists to be added back to its originating core instance or some other core instance. It does not make sense to call functions, other than eles.restore() , on a removed element. A removed element merely exists in this limbo state so you can later add it back to some core instance. Examples Remove selected elements: cy.$( ':selected' ).remove();

ele.removed() Get whether the element has been removed from the graph.

ele.inside() Get whether the element is inside the graph (i.e. not removed).

eles.restore() Put removed elements back into the graph. Details This function puts back elements in the graph that have been removed. It will do nothing if the elements are already in the graph. An element can not be restored if its ID is the same as an element already in the graph. You should specify an alternative ID for the element you want to add in that case. Examples var eles = cy.$( ':selected' ).remove(); eles.restore();

eles.clone() Aliases: eles.copy() , Get a new collection containing clones (i.e. copies) of the elements in the calling collection.

eles.move() et al et al Move the elements with respect to graph topology (i.e. new source , target , or parent ). edges.move( , location ) Change the source, target, or both source and target. location Where the edges are moved. You can specify a new source, a new target, or both. source The ID of the new source node. target The ID of the new target node.

nodes.move( , location ) Change the parent. location Where the nodes are moved. parent The ID of the new parent node (use null for no parent).

Details This function moves the elements in-place, so no remove or add events are generated. A move event is emitted on the moved elements. Examples Move an edge: var ej = cy.$( '#ej' ); ej = ej.move({ target : 'g' });

Events

eles.on() Aliases: eles.bind() , eles.listen() , eles.addListener() , Listen to events that occur on the elements. eles.on( , events [ , selector] , function(event) ) events A space separated list of event names.

selector [optional] A delegate selector to specify child elements for which the handler runs.

function(event) The handler function that is called when one of the specified events occurs. event The event object.

Details Events are bound only to the currently existing elements; they must exist at the time your code makes the call to eles.on() . Alternatively, use core event handlers ( cy.on() ) to attach event handlers. Examples cy.$( '#j' ).on( 'tap' , function ( evt ) { console .log( 'tap ' + evt.target.id() ); });

eles.promiseOn() Aliases: eles.pon() , Get a promise that is resolved the first time any of the elements emit any of the specified events. eles.promiseOn( , events [ , selector] ) events A space separated list of event names.

selector [optional] A selector to specify elements for which the handler is emitted. Examples cy.$( '#j' ).pon( 'tap' ).then( function ( event ) { console .log( 'tap promise fulfilled' ); });

eles.one() Add a listener that is called once per event per element. eles.one( , events [ , selector] , function(event) ) events A space separated list of event names.

selector [optional] A delegate selector to specify child elements for which the handler runs.

function(event) The handler function that is called when one of the specified events occurs. event The event object.

Details For each event specified to this function, the handler function is triggered once per element. This is useful for one-off events that occur on each element in the calling collection once. This function is a bit more complicated for compound nodes where a delegate selector has been specified: Note that the handler is called once per element in the calling collection, and the handler is triggered by matching descendant elements. Examples cy.$( 'node' ).one( 'tap' , function ( e ) { var ele = e.target; console .log( 'tapped ' + ele.id()); });

eles.once() Add a listener that is called once per event per collection. eles.once( , events [ , selector] , function(event) ) events A space separated list of event names.

selector [optional] A delegate selector to specify child elements for which the handler runs.

function(event) The handler function that is called when one of the specified events occurs. event The event object.

Details For each event specified to this function, the handler function is triggered once. This is useful for one-off events that occur on just one element in the calling collection. Examples cy.nodes().once( 'click' , function ( e ) { var ele = e.target; console .log( 'clicked ' + ele.id()); });

eles.removeListener() Aliases: eles.off() , eles.unbind() , eles.unlisten() , Remove one or more listeners on the elements. eles.removeListener( , events [ , selector] [ , handler] ) events A space separated list of event names.

selector [optional] The same delegate selector used to listen to the events.

handler [optional] A reference to the handler function to remove. Examples var j = cy.$( '#j' ); var handler = function ( ) { console .log( 'tap' ) }; j.on( 'tap' , handler); j.on( 'tap' , function ( ) { console .log( 'some other handler' ); }); j.emit( 'tap' ); j.removeListener( 'tap' , handler); j.emit( 'tap' ); j.removeListener( 'tap' );

eles.removeAllListeners() Remove all event handlers on the elements.

eles.emit() Aliases: eles.trigger() , Emit events on the elements. eles.emit( , events [ , extraParams] ) events A list of event names to emit (either a space-separated string or an array)

extraParams [optional] An array of additional parameters to pass to the handler. Examples var j = cy.$( '#j' ); j.on( 'tap' , function ( ) { console .log( 'tap!!' ); }); j.emit( 'tap' );

Data

eles.data() et al et al Aliases: eles.attr() , Read and write developer-defined data associated with the elements. ele.data() Get the entire data object. ele.data( , name ) Get a particular data field for the element. name The name of the field to get. ele.data( , name , value ) Set a particular data field for the element. name The name of the field to set.

value The value to set for the field. ele.data( , obj ) Update multiple data fields at once via an object. obj The object containing name-value pairs to update data fields. Details Only JSON-serialisable data may be put in ele.data() . For temporary data or non-serialisable data, use ele.scratch() . The following fields are normally immutable: id : The id field is used to uniquely identify an element in the graph.

: The field is used to uniquely identify an element in the graph. source & target : These fields define an edge’s relationship to nodes, and this relationship can not be changed after creation.

& : These fields define an edge’s relationship to nodes, and this relationship can not be changed after creation. parent : The parent field defines the parent (compound) node. In order to modify those fields, which alter graph topology, you must use ele.move() . Examples var j = cy.$( '#j' ); j.data( 'weight' , 60 ); j.data({ name : 'Jerry Jerry Dingleberry' , height : 176 }); var weight = j.data( 'weight' );

eles.removeData() Aliases: eles.removeAttr() , Remove developer-defined data associated with the elements. eles.removeData() Removes all mutable data fields for the elements. eles.removeData( , names ) Removes the specified mutable data fields for the elements. names A space-separated list of fields to delete. Details Using ele.removeData() sets the specified fields to undefined . This allows you to use a meaningful null value in your element data. The following data fields are normally immutable, and so they can not be removed: id : The id field is used to uniquely identify an element in the graph.

: The field is used to uniquely identify an element in the graph. source & target : These fields define an edge’s relationship to nodes, and this relationship can not be changed after creation.

& : These fields define an edge’s relationship to nodes, and this relationship can not be changed after creation. parent : The parent field defines the parent (compound) node. To modify the topology of the graph without adding or removing elements, you must use ele.move() . Even so, only parent may be removed by ele.move() . An edge always requires a valid source and target.

ele.scratch() Extension function: This function is intended for use in extensions. Set or get scratchpad data, where temporary or non-JSON data can be stored. App-level scratchpad data should use namespaces prefixed with underscore, like '_foo' . ele.scratch() Get the entire scratchpad object for the element. ele.scratch( , namespace ) Get the scratchpad at a particular namespace. namespace A namespace string. ele.scratch( , namespace , value ) Set the scratchpad at a particular namespace. namespace A namespace string.

value The value to set at the specified namespace. Details This function is useful for storing temporary, possibly non-JSON data. Extensions — like layouts, renderers, and so on — use ele.scratch() namespaced on their registered name. For example, an extension named foo would use the namespace 'foo' . If you want to use this function for your own app-level data, you can prefix the namespaces you use by underscore to avoid collisions with extensions. For example, using ele.scratch('_foo') in your app will avoid collisions with an extension named foo . This function is useful for associating non-JSON data to an element. Whereas data stored via ele.data() is included by ele.json() , data stored by ele.scratch() is not. This makes it easy to temporarily store unserialisable data. Examples var j = cy.$( '#j' ); var fooScratch = j.scratch()._foo = {}; var fooScratch = j.scratch( '_foo' , {}); var fooScratch = j.scratch( '_foo' );

ele.removeScratch() Extension function: This function is intended for use in extensions. Remove scratchpad data. You should remove scratchpad data only at your own namespaces. ele.removeScratch( , namespace ) Remove the scratchpad data at a particular namespace. namespace A namespace string.

ele.id() A shortcut to get the ID of an element.

ele.json() Get or mutate the element's plain JavaScript object representation. ele.json() Get the element's JSON. ele.json( , eleJson ) Mutate the element's state as specified. eleJson For each field in the object, the element's state is mutated as specified. Details This function returns the plain JSON representation of the element, the same format which is used at initialisation, in cy.add() , etc. This function can also be used to set the element’s state using the plain JSON representation of the element. Each field specified in ele.json( eleJson ) is diffed against the element’s current state, the element is mutated accordingly, and the appropriate events are emitted. This can be used to declaratively modify elements. Note that it is much faster to simply specify the diff-patch objects to ele.json() , e.g. ele.json({ data: { foo: 'bar' } }) only updates foo in data . This avoids the cost of diffs on unchanged fields, which is useful when making many calls to ele.json() for larger graphs. Examples Print the JSON for an element: console .log( cy.$( '#j' ).json() ); Make an element selected: cy.$( '#j' ).json({ selected : true });

eles.jsons() Get an array of the plain JavaScript object representation of all elements in the collection. Details This function returns the plain JSON representation of all elements in the collection, the same format which is used at initialisation, in cy.add() , etc. Examples console .log( cy.elements().jsons() );

ele.group() Get the group string that defines the type of the element. Details The group strings are 'nodes' for nodes and 'edges' for edges. In general, you should be using ele.isEdge() and ele.isNode() instead of ele.group() .

ele.isNode() Get whether the element is a node.

ele.isEdge() Get whether the element is an edge.

edge.isLoop() Get whether the edge is a loop (i.e. same source and target).

edge.isSimple() Get whether the edge is simple (i.e. different source and target).

Metadata

node.degree() et al et al node.degree( , includeLoops ) Get the degree of a node. includeLoops A boolean, indicating whether loops are to be included in degree calculations. node.indegree( , includeLoops ) Get the indegree of a node. includeLoops A boolean, indicating whether loops are to be included in degree calculations. node.outdegree( , includeLoops ) Get the outdegree of a node. includeLoops A boolean, indicating whether loops are to be included in degree calculations. nodes.totalDegree( , includeLoops ) Get the total degree of a collection of nodes. includeLoops A boolean, indicating whether loops are to be included in degree calculations. nodes.minDegree( , includeLoops ) Get the minimum degree of the nodes in the collection. includeLoops A boolean, indicating whether loops are to be included in degree calculations. nodes.maxDegree( , includeLoops ) Get the maximum degree of the nodes in the collection. includeLoops A boolean, indicating whether loops are to be included in degree calculations. nodes.minIndegree( , includeLoops ) Get the minimum indegree of the nodes in the collection. includeLoops A boolean, indicating whether loops are to be included in degree calculations. nodes.maxIndegree( , includeLoops ) Get the maximum indegree of the nodes in the collection. includeLoops A boolean, indicating whether loops are to be included in degree calculations. nodes.minOutdegree( , includeLoops ) Get the minimum outdegree of the nodes in the collection. includeLoops A boolean, indicating whether loops are to be included in degree calculations. nodes.maxOutdegree( , includeLoops ) Get the maximum outdegree of the nodes in the collection. includeLoops A boolean, indicating whether loops are to be included in degree calculations. Details Degree : For a node, the degree is the number of edge connections it has. Each time a node is referenced as source or target of an edge in the graph, that counts as an edge connection. Indegree : For a node, the indegree is the number of incoming edge connections it has. Each time a node is referred to as target of an edge in the graph, that counts as an incoming edge connection. Outdegree : For a node, the outdegree is the number of outgoing edge connections it has. Each time a node is referred to as source of an edge in the graph, that counts as an outgoing edge connection. Total degree : For a set of nodes, the total degree is the total number of edge connections to nodes in the set.

Position & dimensions

node.position() Aliases: node.modelPosition() , node.point() , Get or set the model position of a node. node.position() Get the entire position object. node.position( , dimension ) Get the value of a specified position dimension. dimension The position dimension to get. node.position( , dimension , value ) Set the value of a specified position dimension. dimension The position dimension to set.

value The value to set to the dimension. node.position( , pos ) Set the position using name-value pairs in the specified object. pos An object specifying name-value pairs representing dimensions to set. Details A position has two fields, x and y , that can take on numerical values. Examples var x = cy.$( '#j' ).position( 'x' ); var pos = cy.$( '#e' ).position(); cy.$( '#j' ).position( 'y' , 100 ); cy.$( '#e' ).position({ x : 123 , y : 200 });

nodes.shift() Shift the positions of the nodes by a given model position vector. nodes.shift( , dimension , value ) Shift the nodes by one of 'x' or 'y' . dimension The position dimension to shift.

value The value to shift the dimension. nodes.shift( , pos ) Shift the nodes by a position vector. pos An object specifying name-value pairs representing dimensions to shift. Examples cy.$( '#j' ).shift({ x : 10 , y : 20 });

nodes.positions() Aliases: nodes.modelPositions() , nodes.points() , Set the model positions of several nodes with a function. nodes.positions( , function(ele, i) ) Set the positions via a function. function(ele, i) A callback function that returns the position to set for each element. ele The element being iterated over for which the function should return a position to set. i The index of the element when iterating over the elements in the collection.

nodes.positions( , pos ) Set positions for all nodes based on a single position object. pos An object specifying name-value pairs representing dimensions to set. Examples cy.nodes().positions( function ( node, i ) { return { x : i * 100 , y : 100 }; });

node.renderedPosition() Aliases: node.renderedPoint() , Get or set the rendered (on-screen) position of a node. node.renderedPosition() Get the entire rendered position object. node.renderedPosition( , dimension ) Get the value of a specified rendered position dimension. dimension The position dimension to get. node.renderedPosition( , dimension , value ) Set the value of a specified rendered position dimension. dimension The position dimension to set.

value The value to set to the dimension. node.renderedPosition( , pos ) Set the rendered position using name-value pairs in the specified object. pos An object specifying name-value pairs representing dimensions to set.

node.relativePosition() Aliases: node.relativePoint() , Get or set the model position of a node, relative to its compound parent. node.relativePosition() Get the entire relative position object. node.relativePosition( , dimension ) Get the value of a specified relative position dimension. dimension The position dimension to get. node.relativePosition( , dimension , value ) Set the value of a specified relative position dimension. dimension The position dimension to set.

value The value to set to the dimension. node.relativePosition( , pos ) Set the relative position using name-value pairs in the specified object. pos An object specifying name-value pairs representing dimensions to set.

ele.width() et al et al Get the width of the element. The raw width of the element is returned, independent of whether the element is visibile. ele.width() Get the width of the element in model dimensions. ele.outerWidth() Get the outer width of the element in model dimensions (includes width, padding, & border). ele.renderedWidth() Get the width of the element in rendered dimensions. ele.renderedOuterWidth() Get the outer width of the element in rendered dimensions (includes width, padding, & border) in rendered dimensions.

ele.height() et al et al Get the height of the element. The raw height of the element is returned, independent of whether the element is visibile. ele.height() Get the height of the element in model dimensions. ele.outerHeight() Get the outer height of the element in model dimensions (includes height, padding, & border). ele.renderedHeight() Get the height of the element in rendered dimensions. ele.renderedOuterHeight() Get the outer height of the element in rendered dimensions (includes height, padding, & border) in rendered dimensions.

eles.boundingBox() Aliases: eles.boundingbox() , eles.bb() , Get the bounding box of the elements (in model co-ordinates). eles.boundingBox( , options ) Get the bounding box of the elements in model co-ordinates. options An object containing options for the function. includeNodes A boolean indicating whether to include nodes in the bounding box (default true ). includeEdges A boolean indicating whether to include edges in the bounding box (default true ). includeLabels A boolean indicating whether to include labels overall in the bounding box (default true ). This option overrides all other label options if false . includeMainLabels A boolean indicating whether to include main (node or edge) label s in the bounding box (default true ). includeSourceLabels A boolean indicating whether to include (edge) source-label s in the bounding box (default true ). includeTargetLabels A boolean indicating whether to include (edge) target-label s in the bounding box (default true ). includeOverlays A boolean indicating whether to include overlays (such as the one which appears when a node is clicked) in the bounding box (default true ).

Details This function returns a plain object with the fields x1 , x2 , y1 , y2 , w , and h defined. An element that does not take up space (e.g. display: none ) has a bounding box of zero w and h . The x1 , x2 , y1 , and y2 values will have no meaning for those zero-area elements. To get the position of a display: none node, use node.position() instead. Note that the includeOverlays option necessarily includes the dimensions of the body of the element. So using includeOverlays: true with includeNodes: false , for example, does not make sense. The case where the includeOverlays option is only useful in getting the non-overlay dimensions of an element, e.g. { includeOverlays: false, includeNodes: true } .

eles.renderedBoundingBox() Aliases: eles.renderedBoundingbox() , Get the rendered bounding box of the elements. eles.renderedBoundingBox( , options ) Get the bounding box of the elements in rendered co-ordinates. options An object containing options for the function. includeNodes A boolean indicating whether to include nodes in the bounding box (default true ). includeEdges A boolean indicating whether to include edges in the bounding box (default true ). includeLabels A boolean indicating whether to include labels overall in the bounding box (default true ). This option overrides all other label options if false . includeMainLabels A boolean indicating whether to include main (node or edge) label s in the bounding box (default true ). includeSourceLabels A boolean indicating whether to include (edge) source-label s in the bounding box (default true ). includeTargetLabels A boolean indicating whether to include (edge) target-label s in the bounding box (default true ). includeOverlays A boolean indicating whether to include overlays (such as the one which appears when a node is clicked) in the bounding box (default true ).

Details This function returns a plain object with the fields x1 , x2 , y1 , y2 , w , and h defined. An element that does not take up space (e.g. display: none ) has a bounding box of zero w and h . The x1 , x2 , y1 , and y2 values will have no meaning for those zero-area elements. To get the position of a display: none node, use node.position() instead. Note that the includeOverlays option necessarily includes the dimensions of the body of the element. So using includeOverlays: true with includeNodes: false , for example, does not make sense. The case where the includeOverlays option is only useful in getting the non-overlay dimensions of an element, e.g. { includeOverlays: false, includeNodes: true } .

node.grabbed() Get whether a node is currently grabbed, meaning the user has hold of the node.

node.grabbable() Get whether the user can grab a node.

nodes.grabify() Allow the user to grab the nodes. Examples cy.$( '#j' ).grabify();

nodes.ungrabify() Disallow the user to grab the nodes. Examples cy.$( '#j' ).ungrabify();

node.locked() Get whether a node is locked, meaning that its position can not be changed.

nodes.lock() Lock the nodes such that their positions can not be changed. Examples cy.$( '#j' ).lock();

nodes.unlock() Unlock the nodes such that their positions can be changed. Examples cy.$( '#j' ).unlock();

ele.active() Gets whether the element is active (e.g. on user tap, grab, etc).

ele.pannable() Gets whether the element allows passthrough panning. Description A pannable element allows passthrough panning: The user can pan the graph when dragging on the element. Thus, a pannable element is necessarily ungrabbable. By default, an edge is pannable and a node is not pannable.

eles.panify() Enables passthrough panning on the elements. Examples cy.$( '#j' ).panify();

eles.unpanify() Disables passthrough panning on the elements. Examples cy.$( '#j' ).unpanify();

Edge points

edge.controlPoints() et al et al Get an array of control point positions for a curve-style: bezier or curve-style: unbundled-bezier edge. edge.controlPoints() Get the control points in model co-ordinates. edge.renderedControlPoints() Get the control points in rendered co-ordinates. Details Each bezier edge consists of one or more quadratic bezier curves. A quadratic bezier curve is specified by three points. Those points include the start point (P0), the centre control point (P1), and the end point (P2). Traditionally, all three points are called “control points”, but only the centre control point (P1) is referred to as the “control point” within this documentation for brevity and clarity. This function returns the centre control point, as other points are available by functions like edge.targetEndpoint() . The number of returned points for each curve style is as follows: curve-style: bezier (simple edge) : 1 point for a single quadratic bezier

(simple edge) : 1 point for a single quadratic bezier curve-style: bezier (loop) : 2 points for two quadratic beziers

(loop) : 2 points for two quadratic beziers curve-style: unbundled-bezier : n points for n quadratic beziers, as the number of control points is defined by control-point-distances and control-point-weights Notes: While the control points may be specified relatively in the CSS, this function returns the absolute model positions of the control points. The points are specified in the order of source-to-target direction.

This function works for bundled beziers, but it is not applicable to the middle, straight-line edge in the bundle.

For an unbundled bezier edge, the point that joins two successive bezier curves in the series is given by the midpoint (mean) of the two control points. That join point specifies P2 for the first bezier, and it specifies P0 for the second bezier.

edge.segmentPoints() et al et al Get an array of segment point positions (i.e. bend points) for a curve-style: segments edge. edge.segmentPoints() Get the segment points in model co-ordinates. edge.renderedSegmentPoints() Get the segment points in rendered co-ordinates. Details While the segment points may be specified relatively in the stylesheet, this function returns the absolute model positions of the segment points. The points are specified in the order of source-to-target direction.

edge.sourceEndpoint() et al et al Get the position of where the edge ends, towards the source node. edge.sourceEndpoint() Get the source endpoint in model co-ordinates. edge.renderedSourceEndpoint() Get the target endpoint in rendered co-ordinates.

edge.targetEndpoint() et al et al Get the position of where the edge ends, towards the target node. edge.targetEndpoint() Get the target endpoint in model co-ordinates. edge.renderedTargetEndpoint() Get the target endpoint in rendered co-ordinates.

edge.midpoint() et al et al Get the position of the midpoint of the edge. edge.midpoint() Get the midpoint in model co-ordinates. edge.renderedMidpoint() Get the midpoint in rendered co-ordinates. Details The midpoint is, by default, where the edge’s label is centred. It is also the position towards which mid arrows point. For curve-style: unbundled-bezier edges, the midpoint is the middle extremum if the number of control points is odd. For an even number of control points, the midpoint is where the two middle-most control points meet. This is the middle inflection point for bilaterally symmetric or skew symmetric edges, for example. For curve-style: segments edges, the midpoint is the middle segment point if the number of segment points is odd. For an even number of segment points, the overall midpoint is the midpoint of the middle-most line segment (i.e. the mean of the middle two segment points).

Layout

eles.layout() Aliases: eles.createLayout() , eles.makeLayout() , Get a new layout, which can be used to algorithmically position the nodes in the collection. eles.layout( , options ) options The layout options. This function is useful for running a layout on a subset of the elements in the graph, perhaps in parallel to other layouts. You must specify options.name with the name of the layout you wish to use. This function creates and returns a layout object. You may want to keep a reference to the layout for more advanced usecases, such as running multiple layouts simultaneously. Note that you must call layout.run() in order for it to affect the graph. Examples Assign random positions to all nodes: var layout = cy.elements().layout({ name : 'random' }); layout.run(); Apply a circle layout to only the shown elements: var layout = cy.elements().not( ':invisible, :transparent' ).layout({ name : 'circle' }); layout.run();

nodes.layoutPositions() Extension function: This function is intended for use in extensions. Position the nodes for a discrete/synchronous layout. nodes.layoutPositions( , layout , options , function(ele, i) ) layout The layout.

options The layout options object.

function(ele, i) A function that returns the new position for the specified node. ele The node being iterated over for which the function should return a position to set. i The index of the current node while iterating over the nodes in the layout.

This function is intended to be used only by layout extensions. Your app should not call this function directly. This function is called by discrete (synchronous) layouts to update the graph with new node positions. A discrete layout is only responsible for calculating new node positions. Setting these positions and performing animations, modifying the viewport, changing zoom level, etc. are handled by layoutPositions() — which is called by each layout at the end of its run() method. The options object is passed to layoutPositions() when called by a layout extension and consists of many of the common properties shared between layouts: var options = { animate : false , animationDuration : 500 , animationEasing : undefined , animateFilter : function ( node, i ) { return true ; }, eles : someCollection, fit : true , padding : 30 , pan : undefined , ready : undefined , stop : undefined , spacingFactor : 1 , transform : function ( node, position ) { return position; } zoom : undefined } Note that if fit is true, it will override any values provided in pan or zoom .

node.layoutDimensions() Extension function: This function is intended for use in extensions. Get the node width and height. This function is intended for use in layout positioning to do overlap detection. node.layoutDimensions( , options ) options The layout options object. This function is used to retrieve the width and height of the bounding box of a node. The way the width and height are calculated is affected by the options object. This function returns an object containing the width and height of the calculated bounding box under the w and h keys respectively. It can be used as a direct replacement for the boundingBox() function assuming only w and h values are needed. var options = { nodeDimensionsIncludeLabels : true }; var dims = cy.nodes().first().layoutDimensions( options );

Selection

ele.selected() Get whether the element is selected.

eles.select() Make the elements selected. Elements outside the collection are not affected. Examples cy.$( '#j' ).select();

eles.unselect() Aliases: eles.deselect() , Make the elements not selected. Elements outside the collection are not affected. Examples cy.$( '#j' ).unselect();

ele.selectable() Get whether the element's selection state is mutable.

eles.selectify() Make the selection states of the elements mutable. Examples cy.$( '#j' ).selectify();

eles.unselectify() Make the selection states of the elements immutable. Examples cy.$( '#j' ).unselectify();

Style

eles.addClass() Add classes to elements. The classes should be specified in the stylesheet in order to have an effect on the rendered style of the elements. eles.addClass( , classes ) classes An array (or a space-separated string) of class names to add to the elements. Examples cy.$( '#j, #e' ).addClass( 'foo' );

eles.removeClass() Remove classes from elements. The classes should be specified in the stylesheet in order to have an effect on the rendered style of the elements. eles.removeClass( , classes ) classes An array (or a space-separated string) of class names to remove from the elements. Examples cy.$( '#j, #e' ).removeClass( 'foo' );

eles.toggleClass() Toggle whether the elements have the specified classes. The classes should be specified in the stylesheet in order to have an effect on the rendered style of the elements. eles.toggleClass( , classes [ , toggle] ) classes An array (or a space-separated string) of class names to toggle on the elements.

toggle [optional] Instead of automatically toggling, adds the classes on truthy values or removes them on falsey values. Examples Toggle: cy.$( '#j, #e' ).toggleClass( 'foo' ); Toggle on: cy.$( '#j, #e' ).toggleClass( 'foo' , true ); Toggle off: cy.$( '#j, #e' ).toggleClass( 'foo' , false );

eles.classes() et al et al Aliases: eles.className() , eles.classNames() , Get or replace the current list of classes on the elements with the specified list. ele.classes() Get the list of classes as an array for the element. eles.classes( , classes ) Replace the list of classes for all elements in the collection. classes An array (or a space-separated string) of class names that replaces the current class list. Examples Remove all classes: cy.nodes().classes([]); cy.nodes().classes( '' ); Replace classes: cy.nodes().classes([ 'foo' ]); cy.nodes().classes( 'foo' );

eles.flashClass() Add classes to the elements, and then remove the classes after a specified duration. eles.flashClass( , classes [ , duration] ) classes An array (or a space-separated string) of class names to flash on the elements.

duration [optional] The duration in milliseconds that the classes should be added on the elements. After the duration, the classes are removed. Examples cy.$( '#j, #e' ).flashClass( 'foo' , 1000 );

ele.hasClass() Get whether an element has a particular class. ele.hasClass( , className ) className The name of the class to test for. Examples console .log( 'j has class `foo` : ' + cy.$( '#j' ).hasClass( 'foo' ) );

eles.style() et al et al Aliases: eles.css() , Get or override the style of the element. ele.style() Get a name-value pair object containing visual style properties and their values for the element. ele.style( , name ) Get a particular style property value. name The name of the visual style property to get. eles.style( , name , value ) Set a particular style property value. name The name of the visual style property to set.

value The value of the visual style property to set. eles.style( , obj ) Set several particular style property values. obj An object of style property name-value pairs to set. eles.removeStyle() Remove all style overrides. eles.removeStyle( , names ) Remove specific style overrides. names A space-separated list of property names to remove overrides. Details You should use this function very sparingly for setting: There are very few valid usecases for setting with ele.style() .

. It overrides the style of an element, despite the state and classes that it has.

In general, it’s much better to specify a better stylesheet at initialisation that reflects your application state rather than programmatically modifying style.

You can not serialise or deserialise overridden style via ele.json() . Only defined visual style properties are supported. If you would like to remove a particular overridden style property, you can set null or '' (the empty string) to it.

ele.numericStyle() Get the numeric value of a style property in preferred units that can be used for calculations. ele.numericStyle( , name ) name The name of the style property to get. Details Sizes (e.g. width ) are in model pixels.

) are in model pixels. Times (e.g. transition-duration ) are in milliseconds.

) are in milliseconds. Angles (e.g. text-rotation ) are in radians.

) are in radians. Plain numbers (e.g. opacity ) are unitless.

) are unitless. Colours (e.g. background-color ) are in [r, g, b] arrays with values on [0, 255].

) are in arrays with values on [0, 255]. Lists of numbers (e.g. edge-distances ) are in arrays.

) are in arrays. Percents range on [0, 1] so that they are useful for calculations.

Some properties can not have preferred units defined, like background-position-x — it could be in px or % , for instance. A property like this is returned in the units as specified in the element’s style (e.g. the stylesheet). In this case, the units can be returned explicitly via ele.numericStyleUnits() .

— it could be in or , for instance. A property like this is returned in the units as specified in the element’s style (e.g. the stylesheet). In this case, the units can be returned explicitly via . Values that can not be expressed as numbers (e.g. label ) are returned as a string. Examples node.numericStyle('width') would return 30 for a 30px wide node, even if the node was specified as width: 3em .

ele.numericStyleUnits() Get the units that ele.numericStyle() is expressed in, for a particular property. ele.numericStyleUnits( , name ) name The name of the style property to get.

ele.visible() et al et al Get whether the element is visible (i.e. display: element and visibility: visible ). ele.visible() Get whether the element is visible. ele.hidden() Get whether the element is hidden.

ele.effectiveOpacity() Get the effective opacity of the element (i.e. on-screen opacity), which takes into consideration parent node opacity.

ele.transparent() Get whether the element's effective opacity is completely transparent, which takes into consideration parent node opacity.

Animation

ele.animated() Get whether the element is currently being animated.

eles.animate() Animate the elements. eles.animate( , options ) options An object containing the details of the animation. position A position to which the elements will be animated. renderedPosition A rendered position to which the elements will be animated. style An object containing name-value pairs of style properties to animate. duration The duration of the animation in milliseconds. queue A boolean indicating whether to queue the animation (default true ). easing A transition-timing-function easing style string that shapes the animation progress curve. complete A function to call when the animation is done. step A function to call each time the animation steps.

Details Note that you can specify only one of position and renderedPosition : You can not animate to two positions at once. Examples cy.nodes().animate({ position : { x : 100 , y : 100 }, style : { backgroundColor : 'red' } }, { duration : 1000 }); console .log( 'Animating nodes...' );

ele.animation() Get an animation for the element. ele.animation( , options ) options An object containing the details of the animation. position A position to which the elements will be animated. renderedPosition A rendered position to which the elements will be animated. style An object containing name-value pairs of style properties to animate. duration The duration of the animation in milliseconds. easing A transition-timing-function easing style string that shapes the animation progress curve. complete A function to call when the animation is done. step A function to call each time the animation steps.



eles.delay() Add a delay between queued animations for the elements. eles.delay( , duration , comple