How do I get the ID of a clicked node in cytoscape.js?
Asked Answered
C

3

10

This example in the documentation:

  cy.on('click', function(evt){
      console.log( 'clicked ' + this.id() );
});

Results in:

Uncaught TypeError: Object [object Object] has no method 'id' 

And evt.cyTarget.data() returns undefined.

Contribution answered 6/2, 2013 at 20:49 Comment(0)
K
12

The .id() function works on elements, but you don't have an element in your event handler. You bound to the core without any delegate element selector, so you bound to the core itself -- meaning the reference to this points to cy.

This is probably what you meant:

cy.on('click', 'node', function(evt){
      console.log( 'clicked ' + this.id() );
});
Kitts answered 7/2, 2013 at 18:7 Comment(2)
Your code works, I just wonder why the example code from cytoscape.js website cause no id error. cy.on('tap', 'node', function(evt){ var node = evt.target; console.log( 'tapped ' + node.id() ); });Katmandu
evt.target is necessarily a node because of the delegate selector.Kitts
D
9

I use this for 2.x:

    cy.on('tap', 'node', function (evt) {
         console.log(evt.cyTarget.id())
    });

Or for 3.x:

    cy.on('tap', 'node', function (evt) {
         console.log(evt.target.id())
    });
Diary answered 29/4, 2016 at 12:1 Comment(1)
Yes, but how do you access the data from an event in my vue.js 3 component?Tannic
Z
3

As mentioned in the documentation for accessing data, you access element data with the eles.data() method. In your case it would be that you defined the id as the node name, then it's just a matter of calling

console.log('clicked ' + this.data('id'));
Zn answered 7/2, 2013 at 10:23 Comment(2)
Thanks, this results in: Uncaught TypeError: Cannot read property 'id' of undefinedContribution
Actually, it works if I do this (slight modification of github.com/cytoscape/cytoscape.js/blob/master/debug/init.js): gist.github.com/dtenenba/4733384Contribution

© 2022 - 2024 — McMap. All rights reserved.