Search code examples
javascriptvis.jsvis.js-network

How to make a node in vis.js clickable?


I am trying to make node clickable but it is not working

I am beginner in javascript so please help me in this. I have used vis.js library.I want when someone clicks on node then it should redirect to the webpage which is in the url. I tried to do make changes via given examples but it was not working.

Thank you in advance.

var graph ={nodes:[{id:0,group:'Mission Learning',label:"Content Tech + QA",url:'http://www.youtube.com',shape:'box'},{id:1,group:'Mission Learning',label:"Content Hygiene / Launch Automation",url:'http://www.google.com',shape:'box'}],edges:[{from:0,to:1}]};
function destroy() {
  if (network !== null) {
    network.destroy();
    network = null;
  }
}

function draw() {
  destroy();

  var nodes = graph.nodes;
  var edges = graph.edges;
  // randomly create some nodes and edges

  // create a network
  var container = document.getElementById('mynetwork');
  var data = {
    nodes: nodes,
    edges: edges
  };

  var options = {
    edges:{
           color:{color:'white'},
           width: 2,
           arrows: {
                    to: {enabled: true, scaleFactor:.5, type:'arrow'}
           }

    },
    nodes: {
      borderWidth:2,
      size:50,
      color: {
       border: '#222222',
       background: 'grey'
      },
      font:{color:'black',
       size: 40,
       face :'arial',
      },
      margin: {
       top: 20,
       bottom: 20,
       left: 20,
       right: 20
      }
    },
    physics: {
      forceAtlas2Based: {
          gravitationalConstant: -350,
          centralGravity: 0.05,
          springLength: 400,
          springConstant: 0.01,
          avoidOverlap:10
      },
      maxVelocity: 20,
      minVelocity:0,
      solver: 'forceAtlas2Based',
      timestep: 0.10,
      stabilization: {enabled:false,iterations: 0}
    },
    interaction: {
      multiselect: true,
      dragView: true
    }, 
    edges: {
      smooth: false,
      arrows: {to : true }
    }
  };
  network = new vis.Network(container, data, options);

  network.on( 'click', function(properties) {
    var ids = properties.nodes;
    var clickedNodes = nodes.get(ids);
    console.log('clicked nodes:', clickedNodes);

  });
}


Solution

  • What problem do you have?
    Does your code reach the click event?

    Try:

    network.on( 'click', function(properties) {
      console.log('I\'m clicked');
      var ids = properties.nodes;
      var clickedNodes = nodes.get(ids);
      console.log('clicked nodes:');
      console.log(clickedNodes);
    });
    

    Do you get the I'm clicked? at console?
    Do you get the clicked nodes:? at console?
    Do you get any error at console?