block by cherdarchuk 9614216

9614216

Full Screen

Click each shape above to move it to the front.

An ever so slight change to Scott Murray’s implementation, to prevent shapes in the middle of the stack from fading back a little before fading to front.

SVG doesn’t include a concept of z-index, layering, or depth, except that elements that exist later in an SVG document are drawn “on top”. But when designing interactive pieces, we often want shapes that the user has selected / clicked / interacted with to be moved “on top,” to prevent occlusion and ensure visibility.

It’s easy to take an element and simply move it to the bottom of its parent container:

var moveToFront = function() { 
    this.parentNode.appendChild(this); 
}

…but this results in the element jumping into place abruptly. What if we want a smooth transition, like a fade over time?

The sneaky approach demonstrated here:

  1. duplicates the original element
  2. places the duplicate at the end of the parent container (“on top”)
  3. makes the duplicate completely transparent, then fades it in over time
  4. fades out the original over the same period of time
  5. deletes the original once it’s invisible

The visual effect is of an element gradually fading forward, into its new layer position, relative to other elements.

The node-cloning portion of this code is adapted from work by mbostock originally posted on the Google Group.

index.html