3

By adding the onClick event to display a hidden division above each bar in D3.js...

 2 years ago
source link: https://www.codesd.com/item/by-adding-the-onclick-event-to-display-a-hidden-division-above-each-bar-in-d3-js-maybe-i-also-miss-some-important-css-code.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

By adding the onClick event to display a hidden division above each bar in D3.js (maybe I also miss some important css code?)

advertisements

So what I'm trying to do is to have a hidden div, called myDiv, to show up above the clicked bar when each squared bar is clicked.

What I've tried so far is 1) Javascript code for showDiv()

 function showDiv() {
     document.getElementById('myDiv').style.display = "block";
 }

2) HTML code for myDiv

<div id= "myDiv" style="display: none;">
     <p>Detail</p>
</div>

3) CSS for a bar chart

div.bar {
    display:inline-block;
    width: 20px;
    height: 75px;   /* Gets overriden by D3-assigned height below */
    margin-right: 2px;

4) Javascript (D3) code for onClick event on a bar

var dataset = [5, 10, 13, 7, 21, 24, 15, 16];
var bar = d3.select("body").selectAll("div")
            .data(dataset)
            .enter()
            .append("div")
            .attr("class", "bar")
            .style("height", function(d) {
                var barHeight = d * 5;
                return barHeight + "px";
            })
            .style("width", function(d) {
                var barWidth = d * 5;
                return barWidth + "px";
            })
           .on("click", showDiv);

With what I already have show up at an on click event of a bar. But I'm not sure how I can make myDiv to appear above a selected bar.

Please help! Thanks :)


If you haven't already, you should look into jQuery. It's a Javascript library that makes dom manipulation and traversal much easier.

I see that you have the showDiv function working, but now need to make it show only the myDiv above the clicked item. Without your full html markup it's a bit hard to know what you mean. However, looking into the jQuery API for dom traversal might help. For example, .closest might be helpful.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK