HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Optimizing mouse in/out

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
optimizingmouseout

Problem

I have this code that places a marker and on mouse-over this marker is scaled out and then back to the 'original' scale:

this.drawPerson = function () {
   self.svg.append("path")
        .attr("d", personPath)
        .attr("transform", "translate(100,100)scale(0.1)")
        .attr("class", "member")
        .style("fill", "steelblue")
        .on("mouseover", function(){
            d3.select(this).transition()
                .style("fill", "red")
                .attr("transform", "translate(100,100)scale(0.2)")
            })
        .on("mouseout", function() {
            d3.select(this).transition()
                .style("fill", "steelblue")
                .attr("transform", "translate(100,100)scale(0.1)")
            });
}


The x and y are the coordinates for the position on the canvas.

Here is the example: http://jsfiddle.net/SuTZR/8/

Solution

There does not seem to be a great way of solving this.

The best I can propose is to capture the style that you will re-set to into a function and use that function both during initialization and mouseout, this makes the code DRY'er, but not necessarily nicer:

this.drawPerson = function () {

  function style( svg ){
    return svg.style("fill", "steelblue")      
              .attr("transform", "translate(100,100)scale(0.1)");
  }

   style( self.svg.append("path")
        .attr("d", personPath)
        .attr("class", "member") )
        .on("mouseover", function(){
            d3.select(this).transition()
                .style("fill", "red")
                .attr("transform", "translate(100,100)scale(0.2)")
        })
        .on("mouseout", function() {
            style( d3.select(this).transition() )
        });
}

Code Snippets

this.drawPerson = function () {

  function style( svg ){
    return svg.style("fill", "steelblue")      
              .attr("transform", "translate(100,100)scale(0.1)");
  }

   style( self.svg.append("path")
        .attr("d", personPath)
        .attr("class", "member") )
        .on("mouseover", function(){
            d3.select(this).transition()
                .style("fill", "red")
                .attr("transform", "translate(100,100)scale(0.2)")
        })
        .on("mouseout", function() {
            style( d3.select(this).transition() )
        });
}

Context

StackExchange Code Review Q#13935, answer score: 2

Revisions (0)

No revisions yet.