Search code examples
d3.jsbar-chartshow-hideaxis-labels

show div and hide other ones - d3.js


I made a bar chart in d3.js. When I click on one of the ticks, a div appears underneath the bar-graph that is linked to this specific tick. So, there are 24 ticks with 24 matching divs containing information about these ticks.

This works fine, but now I want all others divs to close when I open a new one.

This the code I have so far. I need to press the tick for a second time in order to close it. Bar Chart

d3.selectAll(".tick")
     .on("click",clickme)

function clickme(d){
      var info = document.getElementById(""+d+ "");
      if (info.style.display === "none") {
      info.style.display = "block";
    } else {
      info.style.display = "none";
    }
}

This is what my divs look like

<div style = "display:none" id="Coal CCS retrofit" class = "hidden"> 1 </div>
<div style = "display:none" id="Coal CCS new built" class = "hidden"> 2 </div>

I tried to incorporate this jQuery:

$(document).ready(function () {
  var $answers = $('.hidden');
  $(".member").click(function () {
      var $ans = $(this).next(".hidden").stop(true).slideToggle(100);
      $answers.not($ans).filter('.block').stop(true).slideUp();
  })
});

with the following CSS:

.hidden {
  display:none;
}

When I use the Jquery, the div pops up, and 'slides up' immediately after this. I think this is because the ticks don't have a class 'member', but I can't manage to make it work.


Solution

  • A better solution might be to make your info divs share a common class (e.g. tooltip below), and then hide all of them, before showing the div that was clicked. Sample code:

    <div id="Coal CCS new built" class = "tooltip"> 1 </div>
    <div id="Coal CCS new built" class = "tooltip"> 2 </div>
    
    d3.selectAll(".tick")
         .on("click",clickme)
    
    function clickme(d){
        // Select element that should be shown
        const element = d3.select("#"+d.id); // Or however you're deriving id
    
        // Determine whether the element needs to be shown or hidden
        const show = element.style('display') === 'none';
    
        // Hide any tooltip that may be shown
        d3.selectAll('.tooltip').style('display', 'none');
    
        // Show element, if appropriate
        if (show) element.style('display', 'block');
    }