d3.js, click to link to another URL encoded with variables
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.)
clerksx
Updated on June 14, 2022Comments
-
clerksx almost 2 years
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.
-
clerksx about 12 yearsThanks, but simply I changed function() to function(d) and it worked!!
-
Scott Chu about 9 yearsI use xlink:href on circle ojbect but it doesn't work! It seems that we have to use on("click") solution. By the way, I'm new to D3, how can I add an attribute, say the link url, and get it back in the on("click"... event?
-
methodofaction about 9 years@ScottChu you'd do...
.on("click", function(){ d3.select(this).attr("your-attribute");}
-
rstackhouse almost 5 years
xlink:href
appears to be deprecated now.