user1899082
user1899082

Reputation:

Adding OnClick event to a bar chart

This is all the code that I have, there is something wrong with the "on click" part that I couldn't figure out. It errors and says "drill not defined" Isn't it the way we can call a method on click event of one of those bar charts that I am drawing in the D3 section?

$( document ).ready(function() {

    gon.data.pop(); // get rid of query_time element.
    var dataset = gon.data;

    function drill(d, i) {
        console.log(d.total_count); //data object
        var url = "http://localhost:4567/drill/" + d.brand_name + "/" + d.generic_name;
        window.location.href = url;
    }

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

Upvotes: 0

Views: 9378

Answers (3)

Dancrumb
Dancrumb

Reputation: 27579

Move your declaration of the drill function to outside of your document-ready handler.

Better still, use the on method that d3 provides, rather than the onclick attribute.

Upvotes: 1

BeNdErR
BeNdErR

Reputation: 17927

you can also use jQuery .click() if you want, here's an example

$("#test").click(function(){
     sayHello();   
});

jsfiddle here: http://jsfiddle.net/SGRmX/1/

Upvotes: 0

cyon
cyon

Reputation: 9548

To add event listeners to selections you should use selection's on method.

You can write

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

Upvotes: 7

Related Questions