user1899082
user1899082

Reputation:

Making charts clickable

I am just learning and trying to code it at the same time, this is the code I have, If I take out the drill method and take out the .click(drill) then everything works so far, it draws some silly bar charts from the data I am sending to it

$( document ).ready(function() {


    var dataset = gon.data;

    d3.select("body").selectAll("div")
        .data(dataset)
        .enter()
        .append("div")
        .attr("class", "bar")
        .click(drill)
        .style("height", function(d) {
            return d.brand_name + "px";
        });

    function drill (event) {
        var target = event.currentTarget;
        var data = $(target).data();
        console.log(data);
    }
});  

But I am not able to add "click" event to those bar charts such that when I click on them I can know which chart I clicked on. The code above is result of my unsuccessful attempt to add "click" event to the charts I have drawn .... What is the correct way?

Upvotes: 0

Views: 156

Answers (1)

Elijah
Elijah

Reputation: 4639

You can use .on("click", drill) if you want D3 to pass the object and data attached.

 function drill(d, i) {
      console.log(d); //data object
      console.log(i); //array position
      console.log(this); //DOM element
 }

You can also use .attr("onclick", "drill()") syntax if you want to follow the standard HTML without the D3 wrapper.

Upvotes: 2

Related Questions