简体   繁体   中英

Show / hide element on mouse click in D3

I am trying to make the box appear when you click a node and then disappear if you click off of it. Right now it appears from the get go and it doesn't go away when you click off. Here is the JSFiddle

I tried to I am assuming the edit goes somewhere in here but I can't figure it out for the life of me. I've also checked the other related questions but they have different specific issues.

 var node = svg.selectAll(".node")
  .data(data.nodes)
.enter().append("g")
  .attr("class", "node")
  .on("mouseover", mouseover)
.on("mouseout", mouseout)
 .on("click", function(d) {
  text = "Generic Text Here: " + d.name;
      d3.selectAll(".infobox")  
    //.append("rect")
    //.attr("x", 70)
    //.attr("y", 5)
    //.attr("height", 100)
    //.attr("width", 200) 
    //.select("text")
    .select("a")
    .attr("xlink:href", text) 
    .selectAll("text").text(text)})  
  .call(force.drag);

Thank you thank you

Seems similar to this question: javascript hide/show element

If you prefer not to use jQuery (d3.js can do some of the same things anyways- you know your app best):

///Show. Put in your "mouseout" callback
document.getElementById(id).style.display = 'block';
//Hide. Put in your callback in .on("click", ....
document.getElementById(id).style.display = 'none';

The "id" corresponds to your box. Hope that helps!

EDIT: http://jsfiddle.net/nw7g157c/19/

I had to do a bit of hacking around, but I used the above suggestion to add this:

document.documentElement.onclick = function(e) {
  let evt = e || window.event, // IE...
      target = evt.target || evt.srcElement // IE again...

  if (target.nodeName !== 'circle') { //show the plot box if not a circle:
      document.getElementById('plot').style.display = 'block';
    }
}

and this in your on("click"...)

document.getElementById('plot').style.display = 'none';

Please up vote as it will feed my children

Apart from hide/show I guess you also need to handle scenario where one node clicked and box shown now clicking on another node then the box should be visible with that node data

  if(this.getAttribute("ind") == prev && document.getElementById("plot").style.display == 'block'){
        document.getElementById("plot").style.display = 'none';
    }else{
    document.getElementById("plot").style.display = 'block';}
    prev = i;

See this fiddle http://jsfiddle.net/nw7g157c/9/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM