ObiEff
ObiEff

Reputation: 650

d3 mouse over event doesn't fire correctly if set from function(d)

I am working on a piechart which has a popout animation on mouseover, this is a standard animation I copied from Mike Bostocks example. It works correctly however in my case I have text in the center of the piechart which I would like to change during the mouseover event.

Code can be seen here http://codepen.io/ObiEff/pen/KpzOEz

I have tried to change the event to

.on("mouseover",function (d,i){

                arcTweenOut(radius,0); 
                d3.select("#costTitle")
                .text(data[i].label); 
                d3.select("#cost")
                .text("$"+data[i].value); 

            }) 

Doing this does make the text change correctly, but then the popout of the arc doesn't happen. I have tried several different ways to get them both to fire but can't figure it out.

Without adding function(d) in the mouseover binding the event function only fires once (in my console) and that is on binding of the event, however when it is bound through the function(d) it is fired everytime it is moused over, but does not perform the animation.

Upvotes: 1

Views: 236

Answers (1)

Stephen Gilboy
Stephen Gilboy

Reputation: 5835

It has to do with scope in JavaScript which you can read more about here . I've made your code work by putting the text changes in the function that the arcTweenOut function returns. http://codepen.io/anon/pen/WvxeQw

        function arcTweenOut(outerRadius, delay)
    {   
        // Added parameters to accept what mouseover sends
        return function(a, index) {
          // Added code here to change text/title
            d3.select("#costTitle")
            .text(data[index].label); 
            d3.select("#cost")
            .text("$"+data[index].value); 
          // END NEW CODE
            d3.select(this).transition()
              .delay(delay)
              .attrTween("d",function(d,i) {
                 var i = d3.interpolate(d.outerRadius, outerRadius);
                 return function(t) {
                    d.outerRadius = i(t);
                    return arc(d); 
                };
            });
        };
    }

Upvotes: 2

Related Questions