Search code examples
javascriptd3.js

How do I make specific elements appear on top of others in D3.js?


I have a plot in D3 where I draw some circles and then some ellipses afterwards to show the median. I have a 1.5 second delay on my median, to try and draw it after the circles have appeared, but I still run into problems.

Here is a screenshot of an example: http://puu.sh/8csEK.png

The circle to the far right are behind it's median, the rest of the circles are all in front. When areas are crowded you cannot see the median anymore.

I have even tried using the following on transitions of my circles, but it's no use:

.each("end", <call function to draw ellipses>)

So my question is, how do i make sure that my ellipses are drawn on top of my circles? I have a function that draws my ellipses and a function that draws my circles right now.


Solution

  • I'm assuming that you're using SVG to render your elements. In SVG, the display order is the order of drawing/appending to the DOM. That is, the element you append first is drawn at the back, the element you append last at the front. Child elements (e.g. something underneath a g) are drawn when their parent elements are drawn.

    To make sure that groups of elements have the right order, it's usually easiest to add them to different SVG groups that are drawn in the right order. In code, this looks something like this.

    var circles = svg.append("g");
    var ellipses = svg.append("g");
    // ...
    ellipses.append(...); // this element appears in the front although it is drawn
                          // earlier because it is appended to the group appended last
    circles.append(...); // this element appears behind the one appended to ellipses