Reputation: 459
How to get the tap
event position?
Here, I'm trying to add a node on tap
... but I couldn't figure out how to get the specific coordinates to pass to the rendererPosition
property of the new node.
cy.on('tap', function (e) {
if (e.cyTarget === cy) {
//var pos = $(this).position().left, //tried this, as jquery
//posY = $(this).position().top; //positioning without success
var idNum = cy.nodes().size();
var setID = idNum.toString();
cy.add([{
group: "nodes",
data: {
id: "n" + setID
},
renderedPosition: {
x: e.pageX, //- posX,
y: e.pageY //- posY
},
}]);
}
});
Using the same code but binding with the $('#cy').click
function, it works... but with cy.on('tap')
way, the event e
doesn't have the pageX
and pageY
properties, neither can I get the element position using the $(this).position()
function.
I really prefer using tap
, as I'm trying to develop my application also for mobile interfaces.
Thanks in advance.
EDIT: Using @darshanags observation and this link, I solved this way:
var idNum = cy.nodes().size(),
setID = idNum.toString(),
offset = $("cy").offset(),
position = {
x: e.originalEvent.x - offset.left,
y: e.originalEvent.y - offset.top
};
cy.add([{
group: "nodes",
data: { id: "n" + setID },
renderedPosition: {
x: position.x,
y: position.y
},
...
}]);
Upvotes: 3
Views: 4266
Reputation: 2343
I answered this elsewhere, but had come across both these questions while trying to make this work, so I'll post it here, too.
In cytoscape.js 3.2, there are convenience functions for this:
cy.on("tap", function(e) {
cy.add([{
group: "nodes",
id: "testid",
renderedPosition: {
x: e.renderedPosition.x,
y: e.renderedPosition.y,
},
});
});
This ends up being equivalent to (assuming you've set container: $("#cy-container")
):
cy.on("tap", function(e) {
let canvas = $("#cy-container").find("canvas").get(0);
cy.add([{
group: "nodes",
id: "testid",
renderedPosition: {
x: e.originalEvent.pageX - $(canvas).offset().left,
y: e.originalEvent.pageY - $(canvas).offset().top,
},
});
});
Upvotes: 2
Reputation: 2519
Your usage of is incorrect, Cytoscape's .position()
works a bit differently to jQuery's position()
:
Get the position and use it:
var idNum = cy.nodes().size(),
setID = idNum.toString(),
position = {
x: e.cyTarget.position("x"),
y: e.cyTarget.position("y")
};
cy.add([{
group : "nodes",
data : {
id : "n" + setID
},
renderedPosition : {
x : position.x,
y : position.y
}
}]);
Docs: http://cytoscape.github.io/cytoscape.js/#collection/position--dimensions/node.position
Upvotes: 3