How can I bring a circle to the front with d3?

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);
        }
    });
};

Leave a Comment