How can I bring a circle to the front with d3?
First of all, I am using d3.js to display different sized circles in arrays. On mouse over, I want the circle being moused over to become bigger, which I can do, but I have no idea how to bring it to the front. Currently, once it's rendered, it's hidden behind multiple other circles. How can I fix this?
Here's a code sample:
.on("mouseover", function() {
d3.select(this).attr("r", function(d) { return 100; })
})
I tried using the sort and order methods, but they didn't work. I'm pretty sure i didn't do it correctly. Any thoughts?
TL;DR
With latest versions of D3, you can use selection.raise()
as explained by tmpearce in its answer. Please scroll down and upvote!
Original answer
You will have to change the order of object and make the circle you mouseover being the last element added. As you can see here: https://gist.github.com/3922684 and as suggested by nautat, you have to define the following before your main script:
d3.selection.prototype.moveToFront = function() {
return this.each(function(){
this.parentNode.appendChild(this);
});
};
Then you will just have to call the moveToFront
function on your object (say circles
) on mouseover:
circles.on("mouseover",function(){
var sel = d3.select(this);
sel.moveToFront();
});
Edit: As suggested by Henrik Nordberg it is necessary to bind the data to the DOM by using the second argument of the .data()
. This is necessary to not lose binding on elements. Please read Henrick's answer (and upvote it!) for more info. As a general advice, always use the second argument of .data()
when binding data to the DOM in order to leverage the full performance capabilities of d3.
Edit: As mentioned by Clemens Tolboom, the reverse function would be:
d3.selection.prototype.moveToBack = function() {
return this.each(function() {
var firstChild = this.parentNode.firstChild;
if (firstChild) {
this.parentNode.insertBefore(this, firstChild);
}
});
};
As of d3 version 4, there are a set of built in functions that handle this type of behavior without needing to implement it yourself. See the d3v4 documentation for more info.
Long story short, to bring an element to the front, use selection.raise()
selection.raise()
Re-inserts each selected element, in order, as the last child of its parent. Equivalent to:
selection.each(function() {
this.parentNode.appendChild(this);
});
If you use the moveToFront()
method, make sure you are specifying the second argument to the data()
join method, or your data will be out of synch with your DOM.
d3.js joins your data (provided to a parse()
) method with DOM elements you create. If you manipulate the DOM as proposed above, d3.js won't know what DOM element corresponds to what data 'point' unless you specify a unique value for each data 'point' in the data()
call as the API reference shows:
.data(data, function(d) { return d.name; })