0

How can I use jQuery to interact with SVG generated by Alchemy.js?

I am attempting to use jQuery to interact with SVG elements built by Alchemy.js.

The following code does not work as expected (allowing me to click on a link and see an alert with the value of the element), but when I go into the Firefox console and type manually $("g").on("click", displayNode) the interaction works as expected.

This would appear to be some issue related to the readiness of the SVG elements during script execution (?).

<!doctype html>
<html>
<head>
 <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/alchemyjs/0.4.2/alchemy.min.css" />
 <script src="https://d3js.org/d3.v3.min.js" charset="utf-8"></script>
 <script src="https://cdnjs.cloudflare.com/ajax/libs/alchemyjs/0.4.2/alchemy.min.js"></script>
 <script src="https://cdnjs.cloudflare.com/ajax/libs/alchemyjs/0.4.2/scripts/vendor.js"></script>
 <link rel="stylesheet" type="text/css" href="svg/jquery.svg.css"> 
 <script type="text/javascript" src="svg/jquery.svg.js"></script>
 <script type="text/javascript">
 function displayNode ()
 {
  var label = $(this).find("text").text();

  alert("Clicked on [" + label + "]");
 }

 var config = 
 {
  dataSource: "philosopher.json",
  cluster: true, 
  clusterColours: ["#DD79FF", "#00FF30", "#5168FF", "#f83f00", "#ff8d8f"],
  forceLocked: false,
  nodeCaption: "title", 
  edgeCaption: "relatedness",
  nodeCaptionsOnByDefault: true,
  nodeTypes: {"type":["philosopher"]},
  directedEdges:true,
  nodeStyle: 
  {
   "philosopher": 
   {
    "radius": 18
   }
  }, 
  initialScale: 0.7, 
  initialTranslate: [250,150]
 };
 
 $(function () {
  alchemy = new Alchemy(config);

  $("g.active").on("click",displayNode);
 });
 </script>
</head>
<body>
 <div class="alchemy" id="alchemy"></div>
</body>
</html>
atrobinson
  • 31
  • 2

1 Answers1

0

Try this instead: $('#alchemy').on('click', 'g.active', displayNode);

Without knowing much about alchemy.js, I would presume that it dynamically adds DOM elements to the page that jQuery doesn't know about on page load. I suspect that jQuery therefore cannot find 'g.active' and cannot append a click listener to it.

You must then use a parent node to locate or register your on-click. You could alternatively use $('body').find(....) - I suggest playing around in the JavaScript console (found in most browsers by hitting F12) and attempting to test how you might interface with Alchemy.js

Porschiey
  • 1,981
  • 2
  • 17
  • 25
  • Thank you for the suggestion, but it was unsuccessful. What's more, the suggested code does NOT work when entered from the development tools console (whereas the original "$('g').on('click',displayNode)" DOES work when entered from the development tools console). – atrobinson Jul 18 '17 at 10:46
  • :/ sorry to hear. I perhaps do not know enough about alchemy.js to contribute a working answer. – Porschiey Jul 18 '17 at 14:50