Edit in JSFiddle

var width = 960,
    height = 500;

var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height);

var red_rect = svg.append("g")
    .attr("transform", "translate(" + 50 + "," + 50 + ")")
    .on("mouseover", flash("mouseover", "0"))
    .on("mouseout", flash("mouseout", "1em"));

red_rect.append("rect")
    .attr("x", 0)
    .attr("y", 0)
    .attr("width", 200)
    .attr("height", 200)
    .attr("fill", "red")
    .attr("opacity", 0.5);

red_rect.append("rect")
    .attr("x", 25)
    .attr("y", 25)
    .attr("width", 150)
    .attr("height", 150)
    .attr("fill", "red")
    .attr("opacity", 1);

red_rect.append("text")
    .attr("x", 100)
    .attr("y", 100)
    .style("font-size", "14pt")
    .style("fill", "white")
    .style("stroke", "white")
    .attr("text-anchor", "middle")
    .text("mouseover & out");

var blue_rect = svg.append("g")
    .attr("transform", "translate(" + 300 + "," + 50 + ")")
    .on("mouseenter", flash("mouseenter", "-1em"))
    .on("mouseleave", flash("mouseleave", "2em"));

blue_rect.append("rect")
    .attr("x", 0)
    .attr("y", 0)
    .attr("width", 200)
    .attr("height", 200)
    .attr("fill", "blue")
    .attr("opacity", 0.5)

blue_rect.append("rect")
    .attr("x", 25)
    .attr("y", 25)
    .attr("width", 150)
    .attr("height", 150)
    .attr("fill", "blue")
    .attr("opacity", 1);

blue_rect.append("text")
    .attr("x", 100)
    .attr("y", 100)
    .attr("text-anchor", "middle")
    .style("font-size", "14pt")
    .style("fill", "white")
    .style("stroke", "white")
    .text("mouseenter & leave");


function flash(name, dy) {
  return function() {
    d3.select(this).append("text")
        .attr("transform", "translate(" + d3.mouse(this) + ")")
        .attr("dy", dy)
        .text(name)
        .transition()
        .duration(1500)
        .style("opacity", 0)
        .remove();
  };
}