Adding anchor tag to SVG circles appended with D3 - svg

I have an SVG symbols map I have generated with D3. The map contains over 100 symbols. My question is, How can I add an anchor tag to each individual circle? I will pull the links for each symbol from an external CSV file, but at this point I cannot for the life of me figure out how to add an anchor to each symbol.
My symbols are generated/appended as follows:
circles.selectAll("circles")
.data(schools)
.enter().append("svg:circle")
.attr("cx", function(d,i) {return positions[i][0]})
.attr("cy", function(d,i) {return positions[i][1]})
.attr("r", function(d,i) {return 6})
.attr("i", function(d,i) {return i})
.attr("class", "symbol")
.on("mouseover", function(d,i){
var index = $(this).attr("i");
// console.log(d); ****This is all the data - ie: Name, lat, long, index, state, etc..
return show_bubble(d, index);
}).on("mouseout", function(){
return hide_bubble();
}).on("mousemove", function() {
return move_bubble();
})
I have tried:
d3.selectAll("#circles")
.append("a")
.attr("href", "google.com");
This, however simply wraps my entire group containing the symbols in an anchor tag.
Please help!

The way I usually do text in circles is I do another binding of the data, but instead of appending a circle, I would append text.
So the code could look like this:
circles.selectAll("circle-text")
.data(schools)
.enter().append("text")
.attr("x", function(d,i) {return positions[i][0]})
.attr("y", function(d,i) {return positions[i][1]})
.text( function (d) { return "Hello World" });
And then if you want anchor tags instead of plain text, try reading this example: Hyperlinks in d3.js objects
It seems you need a special element: "svg:a" in order to create hyperlinks.
Hope this helps.

Related

d3 on click for circles not working

I have a simple, modified version of the cluster diagram from D3 that I'm trying to get to respond to mouse clicks. It works for the links between nodes but not the nodes themselves. It looks to me like I'm treating lines and nodes (svg circles) the same, and yet nodes do not work... but of course D3 itself is generating those lines...
I have a very simple demo of it on JSFiddle at: http://jsfiddle.net/gaelicmichael1965/c2XWg/8/
What's going on? I would certainly appreciate any help that could be offered.
var nodes = tree.nodes(flareData),
links = tree.links(nodes);
// Create all of the link paths (using diagonal projection)
// Uses D3 functions to create SVG elements
var link = vis.selectAll(".link")
.data(links)
.enter().append("path")
.attr("class", "link")
.attr("d", diagonal)
.on("click", function(d, index) {
console.log("Selected line");
});
// Create all of the g-elements that contain node svg-elements
var node = vis.selectAll(".node")
.data(nodes)
.enter()
.append("circle")
.attr("class", "node")
.attr("r", 4.5)
.attr("transform", function(d) { return "rotate(" + (d.x - 90) + ")translate(" + d.y + ")"; })
// In actuality, will need to access property of d
.style( "fill", function(d, index) { return fillColors[index%4] } )
.on("click", function(d, index) {
console.log("Selected node");
});
The issue you have stems from your CSS. In particular, you are turning off pointer events for the nodes, meaning that mouse-triggered events (such as "click") are not processing:
.node {
font-size: 12px;
pointer-events: none; /*Comment out or remove this line*/
}
Comment out or remove the pointer-events:none; line in your CSS to allow the nodes to be the target of your "click" event.

SVG D3.js append element to SVG g:circle on text mouseover

Scratching my head on this one.
We have a list of text on the left side of the page. Each item in the list has a data-id attribute that makes it easy to match up corresponding schools in our SVG map. This SVG map is a map of the US, and has school locations fed in from a CSV excel sheet and stored in "schools" for access.
circles.selectAll("circles")
.data(schools)
.enter().append("svg:a")
.attr("xlink:href", function(d) { return d.url; })
.append("svg:circle")
.attr("school", function(d, i) { return d.name; })
.attr("id", function(d, i) { return d.id; })
.attr("cx", function(d,i) { return d.longitude; })
.attr("cy", function(d,i) { return d.latitude; })
.attr("r", function(d,i) { return 6; })
.attr("i", function(d,i) { return i; })
.attr("class", "icon")
So when a user hovers over this list of text I previously mentioned, I use this function:
mapSearch = function(id) {
d3.selectAll("circle")
.filter(function(d) {
if (d.id == id) {
return show_bubble_2(d);
}
})
}
Which calls:
show_bubble_2 = function(school_data) {
var school_info = school_data,
latitude = school_info.latitude,
longitude = school_info.longitude;
bubble.css({
"left": (longitude - 75)+"px",
"top": (latitude - 67)+"px"
});
bubble.html("<h1>" + school_info.name + "</h1>" + "<p>" + school_info.city + ", " + school_info.state + "</p>")
.attr("class", function(d) { return school_info.letter; });
bubble.addClass("active");
}
This works unless we start resizing the map to fit different screen sizes, or unless we do special zoom functions on the map. Then the bubbles closer to the west coast are where they're supposed to be but the ones on the east coast are way off. In short, it's a complete nightmare and not at all scalable.
My question: How do I just append this DIV to the corresponding circle ID instead of using an absolute positioned DIV so that no matter what size the map is, the bubble will always pop up right on top of that circle.
I have tried appending inside the if (d.id == id) { } but it always returns errors and so far I haven't figured it out. I'll keep trying something along those lines because I feel like that's the way to do it. If you have a better solution or could point me in the right direction, I would really appreciate it.
Thanks, and have a good one!
You can find the position of the circle even if there is a transform applied by using Element.getBoundingClientRect.
You could use your filtered selection, get the .node() and find its bounding rect. Then by adjusting for the scroll position, you can find the values of top and left to give to your bubble.
This means that the position of the bubble is based on the actual position at which the circle appears on the page, rather than being based on its data, which would require you to take the transforms into account. Try something like this:
mapSearch = function(id) {
// get the selection for the single element that matches id
var c = d3.selectAll("circle")
.filter(function(d) {
if (d.id == id) {
return show_bubble_2(d);
}
});
// get the bounding rect for that selection's node (the actual circle element)
var bcr = c.node().getBoundingClientRect();
// calculate the top/left based on bcr and scroll position
var bubbleTop = bcr.top + document.body.scrollTop + 'px',
bubbleLeft = bcr.left + document.body.scrollLeft + 'px';
// set the top and left positions
bubble.css({
'top': bubbleTop,
'left': bubbleLeft
});
}
Of course, if you are zooming or panning and want the bubble to remain on the circle, you will need to recalculate these values inside your zoom and pan functions, but the process would be the same.
HERE is a demo using circles that are randomly placed within a g element that has a translation and scale applied. Click on an item in the list to place the bubble on the corresponding circle.
A <div> is HTML. A <circle> is SVG. You can't (easily) put HTML elements inside SVG. You'd have to use <foreignobject> elements to do that. (See this question for details.) Alternatively, you could use native SVG elements such as <tspan> instead of <div>

How to add single label per svg element?

I'm attempting to add a simple data label to this example
svg.selectAll("text")
.data(data)
.enter()
.append("text")
.attr("text-anchor", "middle")
.attr("fill", "red")
.text(function(d) { return d[0] });
but it writes all the data in all labels which I think is because the graph is split over several individual svg-elements. How can I fix this?
Fiddle
You're already binding the data to the SVGs, so there's no need for you to bind it again to the text elements. svg is actually the selection of SVGs here, so all you have to do is
svg.append("text")
.attr("text-anchor", "middle")
.attr("fill", "red")
.text(function(d) { return d[0] });
Complete example here.

How to show a tooltip with value when mouseover a svg line graph using d3.js?

I'm using D3.js. I want to show a tooltip with corresponding Y-axis value when i mouseover d3.svg.line().
I tried using this code:
d3.svg.line().append("title")
.text(function(d) { return d; });`
but it throws error has no method 'append'. Is there any other way?
d3.svg.line() is a line generator; it is not the actual line element. This function is designed to work with an area generator, though you can disable the appearance of the shape within by using "fill:none." For more detailed information, here is a link to its documentation: https://github.com/mbostock/d3/wiki/SVG-Shapes#wiki-line.
The code below creates a path element using the d3.svg.line() generator and then adds a tooltip to the path it generates. This title's text attribute shows the y-value of wherever the mouse is. This is done by using the mouse event "mousemove" which seems to be more what you want instead of using "mouseover." (Mouseover requires you to move in and out of the shape to update the text value, whereas mousemove will change the value even if your mouse moves along the line.)
var data = [[{x:100, y:200}, {x:0,y:400}, {x:2, y:300}]];
var line = d3.svg.line()
.x(function(d) { return d.x; })
.y(function(d) { return d.y; })
.interpolate("basis");
var svg = d3.select("body").append("svg:svg")
.attr("width", 400)
.attr("height", 400);
var g = svg.selectAll("g").data(data).enter().append("svg:g")
.attr("width", 400)
.attr("height", 400);
g.append("path")
.attr("d", line)
.attr("id", "myPath")
.attr("stroke", "black")
.attr("stroke-width", 5)
.attr("fill", "none") // Remove this part to color the
// shape this path produces
.on("mousemove", mMove)
.append("title");
function mMove(){
var m = d3.svg.mouse(this);
d3.select("#myPath").select("title").text(m[1]);
}
There was a little error in your answer.
d3.svg.mouse(this)
doesn't work.
The correct answer is
d3.mouse(this)

Accessing D3 SVG object within on click event

I am working on a bubble graph and I have attached an on click event to each of the circles. When clicking on a circle, the bubble graph will be replaced with a new graph representing a more detailed information.
Here is part of the code:
svg.selectAll("circle")
.data(dataset)
.enter()
.append("circle")
.attr("cx", function(d) {
return scaleX(d[2]);
})
.attr("cy", function(d) {
return scaleY(100 - d[1]);
})
.attr("r", function(d) {
return d[1];
})
.attr("fill", "#4eb157")
.attr("stroke", "#00c4d4")
.attr("stroke-width", function(d) {
return d[1]*(1-d[2]/100)*1.5;
})
.on("click", function ()
{
svg.selectAll("circle")
.data(new_dataset)
.enter()
.append("circle")
.attr("cx", function(d) {
return scaleX(d[2]);
})
.attr("cy", function(d) {
return scaleY(100 - d[1]);
})
.attr("r", function(d) {
return d[1];
})
.attr("fill", "#4eb157")
.attr("stroke", "#00c4d4")
.attr("stroke-width", function(d) {
return d[1]*(1-d[2]/100)*1.5;
});
svg.selectAll("text")
.data(new_dataset)
.enter()
.append("text")
.text(function(d) {
return d[0];
})
.attr("x", function(d) {
return scaleX(d[2]);
})
.attr("y", function(d) {
return scaleY(100 - d[1]);
})
.attr("font-family", "sans-serif")
.attr("font-size", "11px")
.attr("fill", "red");
});
The problem comes when I click on the circle, the whole graph disappears, but no new graph is visualized. I figured out that during the execution of the on click function, the svg object has changed from its initial state and in particular some of the properties such as baseURI, clientHeight, clientWidth etc are not set anymore even though they were when initially creating the svg object. Here is the code with which I am creating the svg object:
var svg = d3.select("body").append("svg")
.attr("width", w)
.attr("height", h);
My question is why is the new graph not appearing? Is this because of the changed properties of the svg object? What should I change in the on click function in order to make the new graph visualize successfully?
Thanks!
The problem is that in the onclick event you are selecting all the circles under the svg element and joining them with new_dataset. You probably want to select another set of circle elements and join new_dataset to this group of circles. One way to do that is to create two groups under svg, one for the original set, and other for the circles of new_dataset, another solution is to assign different classes to different groups of circles and narrow each selection using the class.
In the following links you can find a clearer explanation about the joining mechanism:
D3 Tutorial - Scott Murray
Thinking with Joins - Mike Bostok

Resources