clerksx
clerksx

Reputation: 640

d3.js, click to link to another URL encoded with variables

I made a scatter plot, and want to add a link to each dot.

    chart.selectAll("scatter-dots")
      .data(data)
      .enter().append("circle")
        .attr("cx", function (d) { return x(d.position[0]); } )
        .attr("cy", function (d) { return y(d.position[1]); } )
        .attr("r", 4)
        .style("fill", "#666")
        .style("opacity", 0.5)
    .on("click", function(){
        var url = "http://somelink.com/link.php?id=";
        url += d.link_id;
        //$(location).attr('href', url);
        //window.location = url;    
    });

It works if I just put the pure String link such as window.location = "http://stackoverflow.com" However, if I add queries to the end of the URL from a variable, the page does not redirected.

Neither jquery nor javascript worked (as commented.)

I also tried an external js file, still fail.

This is in a PHP file, if this helps.

Upvotes: 2

Views: 13735

Answers (1)

methodofaction
methodofaction

Reputation: 72415

If it works with a static string then something is wrong with d.link_id. Try seeing what's inside either by doing alert(d.link_id) or if you use a firebug or similars do console.log(d.link_id).

Alternatively, you should use real anchors for linking your nodes instead of setting click events. This would go something like...

chart.selectAll("scatter-dots")
  .data(data)
  .enter()
  .append("a")
    .attr("xlink:href", function(d) {return "http://somelink.com/link.php?id=" + d.link_id})
    .append("circle")
      .attr("cx", function (d) { return x(d.position[0]); } )
      .attr("cy", function (d) { return y(d.position[1]); } )
      .attr("r", 4)
      .style("fill", "#666")
      .style("opacity", 0.5)

(I can't seem to recall if this is the exact way of doing it, you might need to save the anchors in a variable and then append the circles to them.)

Upvotes: 9

Related Questions