2

I am making a d3 choropleth that assigns initial fill property values according to a colorization algorithm to the tune of:

  svg.selectAll(".foo")
      .style("fill", function(d){ 
        return colorization(getRandomArbitrary(5,25)); //returns hex value
      })

This works. Unfortunately, it seems to render my CSS rule irrelevant. The rule works without making the call to .style() via d3:

  .foo:hover{
    fill: white;
  }

I'm not sure if this is something that d3.js is doing, or a result of some sort of interplay between SVG styles and CSS styles.

I am looking for a solution that accomplishes the algorithmic colorization and continues to permit the :hover fill effect.

Alexander O'Mara
  • 58,688
  • 18
  • 163
  • 171
Michael Pell
  • 1,416
  • 1
  • 14
  • 17

2 Answers2

4

This is the expected behavior of CSS and is not unique to SVG or D3. Inline styles override :hover styles. You can override it using !important.

.foo:hover {
    fill: white !important;
}
Alexander O'Mara
  • 58,688
  • 18
  • 163
  • 171
  • Thank you. This was sloppy on my part. I didn't realize that .style() appended the style inline, though in retrospect it is obvious. – Michael Pell Jul 04 '14 at 21:29
3

@Alexander O'Mara 's answer is excellent, however, since you said you are '...looking for a solution that accomplishes the algorithmic colorization...', I just want to bring to your attention another, different, approach.

You can explicitly, programmaticaly, set hover effect with these lines:

svg.selectAll(".foo")
    .style("fill", function(d){ 
        return colorization(getRandomArbitrary(5,25)); //returns hex value
    })
    .on("mouseover", function() { d3.select(this).style("fill", "white") } )
    .on("mouseout", function() { function(d){ 
        return colorization(getRandomArbitrary(5,25));
    })

That way you don't need anything in css file - so there is nothing to be 'overwritten'. :)

Unfortunately, one can't directly convert ":hover" styles from css to inline styles - event handlers must be used, like in the code above!

This is inspired by the solution of this question.

Community
  • 1
  • 1
VividD
  • 10,456
  • 6
  • 64
  • 111