title: D3 Force Layout: Adding & Removing Nodes On Click
body: <p>I can't seem to find any other examples which have a similar application to what I'm trying to do, so I thought I'd just ask.</p>
  
  <p>I'm trying to mock up a funky mind map tool using the awesome d3.js library from mike bostock. I'm still trying to learn d3 and as it also turns out, basic coding! What I want to have is a blank canvas, and 3 buttons; 'add', 'remove' &amp; 'edit'. Very basic I hope!</p>
  
  <ol>
  <li><p>When you select the 'add' button (the top image), and then click on the blank canvas, a node will be added. If you click again nearby, another node will be added and will be linked to the first node.</p></li>
  <li><p>Selecting the 'remove' button (the middle image) then clicking on a node will delete that node and all touching links.</p></li>
  <li><p>Selecting the 'edit' button (the bottom image) will allow you to label nodes.</p></li>
  </ol>
  
  <p>I have step 1 down, and half of step 2. The problem I'm running into goes like this:</p>
  
  <ol>
  <li>Click 'add' button once, add function turned 'on'. <strong>Works</strong></li>
  <li>Add some nodes. <strong>Works</strong></li>
  <li>Click 'add' button again, add function turned 'off'. <strong>Works</strong></li>
  <li>Click the canvas, no nodes are added, but existing nodes are drag-able. <strong>Works</strong></li>
  <li>Click 'remove' button once, remove function turned 'on'. <strong>Works</strong></li>
  <li>Click a node to remove it. <strong>Broken</strong>. Removes everything.</li>
  <li>Click 'remove' button again, remove function turned 'off'. <strong>Broken</strong></li>
  <li>Click 'add' button again, add function turned 'on'. <strong>Broken</strong></li>
  </ol>
  
  <p>Does anyone have any suggestions as to why I'm having this problem &amp; how they would go about solving this? I think it has something to do with confusion between state selection. When turning off the 'remove' function, it calls the same function as when you turn off the 'add' function, so it doesnt know what to do and does nothing... I thought that they should not be mutually selectable, but is one state remaining on after it is switched on? I am really stumped :(</p>
  
  <p>I hope there may be parts of this that are useful to other people as well.
  Thanks!
  Seb</p>
  
  <p>.js below..>>>></p>
  
  <pre><code>//==D3 STUFFS ======================================================
  
  //height &amp; width of the interactive area
  var divh = document.getElementById('container').offsetHeight;
  var divw = document.getElementById('container').offsetWidth;
  
  //node size
  var radius = 20;
  
  //define the nodes and links as empty data sets
  var nodes = [];
  var links = [];
  
  //place the interactive area onto the browser UI with the dimensions defined above
  var interactiveArea = d3.select("#container").append("svg:svg").attr("width", divw).attr("height", divh);
  
  //enable dragging of node elements
  var drag = d3.behavior.drag()
      .origin(Object)
      .on("drag", dragmove);
  
  //define the physics parameters that will take effect on the nodes and links
  var force = d3.layout.force()
      .gravity(0.01)
      .charge(-80)
      .linkDistance(60)
  .nodes(nodes)
  .links(links)
  .size([divw, divh]);
  
  //apply the physics parameters defined above on the nodes and links
  
  force.on("tick", function() 
      {
      interactiveArea.selectAll("line.link")
    .attr("x1", function(d) { return d.source.x; })
    .attr("y1", function(d) { return d.source.y; })
    .attr("x2", function(d) { return d.target.x; })
    .attr("y2", function(d) { return d.target.y; });
  
      interactiveArea.selectAll("circle.node")
    .attr("cx", function(d) { return d.x; })
    .attr("cy", function(d) { return d.y; }); 
      });
  
  //update the position of the object on drag
  
  function dragmove(d) 
      {
  d3.select(this)
    .attr("cx", d.x = Math.max(radius, Math.min(divw - radius, d3.event.x)))
    .attr("cy", d.y = Math.max(radius, Math.min(divh - radius, d3.event.y)));
      }
  
  //update the force layout
  
  function update() 
      {
  interactiveArea.selectAll("line.link")
    .data(links)
    .enter().insert("svg:line", "circle.node")
    .attr("class", "link")
    .attr("x1", function(d) { return d.source.x; })
    .attr("y1", function(d) { return d.source.y; })
    .attr("x2", function(d) { return d.target.x; })
    .attr("y2", function(d) { return d.target.y; });
  
  interactiveArea.selectAll("circle.node")
    .data(nodes)
    .enter().insert("svg:circle", "circle.cursor")
    .attr("class", "node")
    .attr("cx", function(d) { return d.x; })
    .attr("cy", function(d) { return d.y; })
    .attr("r", 10)
    .call(force.drag);
  
  force.start();
      }
  
  //==============================================================
  
  
  //==BUTTON &amp; EVENT SELECTOR=======================================
  
  var addCounter = 0;
  var removeCounter = 0;
  var editCounter = 0;
  
  function addButton_Off()
      {
      //alert("ADD - off");
      document.images["add-button"].src = "love.lost.PNG";
      all_Off();
      return true;
      }
  
  function removeButton_Off()
      {
      //alert("REMOVE - off");
      document.images["remove-button"].src = "love.lost.PNG";
      //all_Off();
      return true;
      }
  
  function editButton_Off()
      {
      //alert("EDIT - off");
      document.images["edit-button"].src = "love.lost.PNG";
  
      return true;
      }
  
  function addButton()
      {
      addCounter++;
      if (addCounter%2 == 0)
          addButton_Off();
      else
          addButton_On();
          if (removeCounter%2 == 1)
              removeCounter++;
              removeButton_Off();
          if (editCounter%2 == 1)
              editCounter++;
              editButton_Off();
  
      function addButton_On()
          {
          //alert("ADD - on");
          document.images["add-button"].src = "pop.cloud.PNG";
          add_Nodes();
          return true;
          }
      }
  
  function removeButton()
      {
      removeCounter++;
      if (removeCounter%2 == 0)
          removeButton_Off();
      else
          removeButton_On();
          if (addCounter%2 == 1)
              addCounter++;
              addButton_Off();
          if (editCounter%2 == 1)
              editCounter++;
              editButton_Off();
  
      function removeButton_On()
          {
          //alert("REMOVE - on");
          document.images["remove-button"].src = "pop.cloud.PNG";
          remove_Nodes();
          return true;
          }
      }
  
  function editButton()
  
      {
      editCounter++;
      if (editCounter%2 == 0)
          editButton_Off();
      else
          editButton_On();
          if (addCounter%2 == 1)
              addCounter++;
              addButton_Off();
          if (removeCounter%2 == 1)
              removeCounter++;
              removeButton_Off();
  
      function editButton_On()
          {
          //alert("EDIT - on");
          document.images["edit-button"].src = "pop.cloud.PNG";
          return true;
          }
      }
  
  //=============================================================
  
  //==EVENT ACTIONS========================================================
  
  function all_Off()
      {
      interactiveArea.on("mousedown", function() 
          {
          update();
          });
      }
  
  
  function add_Nodes()
      {
      //do the following actions when the mouse is clicked on the interactiveArea
      interactiveArea.on("mousedown", function() 
              {
              // add a node under the mouse cursor
              var point = d3.svg.mouse(this),
                  node = {x: point[0], y: point[1]},
                  n = nodes.push(node);
  
              nodes.forEach(function(target) 
                  {
                  var x = target.x - node.x,
                      y = target.y - node.y;
                  //if there is a node less than 30 pixels? away, add a link between the 2 nodes
                  if (Math.sqrt(x * x + y * y) &lt; 30)
                      {
                      // add links to any nearby nodes
                      links.push({source: node, target: target});
                      }
                  });
              update();
              });
      }
  
  function remove_Nodes()
      {
      interactiveArea.on("click", function()
          {
          var point = d3.select(this);
          point.remove();
          update();
          });
      }
  
  
  //function edit_Nodes()
  
  //==========================================================
  </code></pre>
  
  <p>html below...>>>></p>
  
  <pre><code>&lt;html&gt;
      &lt;head&gt;
          &lt;meta http-equiv="Content-Type" content="text/html;charset=utf-8"&gt;
          &lt;link type="text/css" rel="stylesheet" href="style.css"&gt;
          &lt;script src="http://code.jquery.com/jquery-latest.js"&gt;&lt;/script&gt;
      &lt;/head&gt;
  
      &lt;body&gt;
          &lt;div id="enclosure"&gt;
              &lt;div id="title"&gt;
              /
              &lt;/div&gt;
              &lt;div id="button-menu"&gt;
  
                  &lt;a onMouseDown="return addButton()"&gt;
                      &lt;img name="add-button" id="add-button-img" src="love.lost.PNG" width="80px" height="80px" border = "0" alt="fuchs"&gt;
                  &lt;/a&gt;
                  &lt;a onMouseDown="return removeButton()"&gt;
                      &lt;img name="remove-button" id="remove-button-img" src="love.lost.PNG" width="80px" height="80px" border = "0" alt="fuchs"&gt;
                  &lt;/a&gt;
                  &lt;a onMouseDown="return editButton()"&gt;
                      &lt;img name="edit-button" id="edit-button-img" src="love.lost.PNG" width="80px" height="80px" border = "0" alt="fuchs"&gt;
                  &lt;/a&gt;
  
              &lt;/div&gt;
              &lt;div id="container"&gt;
                  &lt;script type="text/javascript" src="http://mbostock.github.com/d3/talk/20111116/d3/d3.js"&gt;&lt;/script&gt;
                  &lt;script type="text/javascript" src="http://mbostock.github.com/d3/talk/20111116/d3/d3.geom.js"&gt;&lt;/script&gt;
                  &lt;script type="text/javascript" src="http://mbostock.github.com/d3/talk/20111116/d3/d3.layout.js"&gt;&lt;/script&gt;
                  &lt;script type="text/javascript" src="bonquiqui.js"&gt;&lt;/script&gt;
                  &lt;!--&lt;script type="text/javascript" src="origin.js"&gt;&lt;/script&gt;--&gt;
  
              &lt;/div&gt;
          &lt;/div&gt;
      &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>css below..>>>></p>
  
  <pre><code>body {
    font: 300 36px "Lane - Posh";
    height: 100%;
    width: 100%;
    margin: auto;
    overflow: hidden;
    position: absolute;
    text-align: center;
    background: #fff;
  }
  
  #enclosure {
    margin-top: 3%;
   }
  
  #title {
  background: #fff;
  font: 300 220% "Lane - Posh";
  height: 100px;
  width: 60%;
  margin-left: auto;
  margin-right: auto;
  }
  
  #button-menu {
  background: #eee;
  height: 20%;
  width: 4%;
  position: absolute;
  top: 48.0%;
  left: 81%;
  } 
  
  #add-button {
  cursor: pointer;
  position: relative;
  top: 5%;
  }
  
  #remove-button {
  cursor: pointer;
  position: relative;
  top: 5%;
  }
  
  #edit-button {
  cursor: pointer;
  position: relative;
  top: 5%;
  }
  
  #container {
    height: 60%;
    width: 60%;
    margin: auto;
    margin-top: 1%;
    background: #eee;
    overflow: hidden;
  }   
  
  circle.node 
    {
    cursor: pointer;
    stroke: #000;
    stroke-width: .5px;
    }
  
  line.link 
    {
    fill: none;
    stroke: #9ecae1;
    stroke-width: 1.5px;
    }
  </code></pre>