Reputation: 300
I am trying to add a hover effect to each bar within my D3 bar chart, attr() is not recognising my CSS styles for some reason.
JS
const url =
"https://raw.githubusercontent.com/freeCodeCamp/ProjectReferenceData/master/GDP-data.json";
d3.select('#svg')
.attr('height', 400)
.attr('width', 800)
// render gdpBars
d3.json(url)
.then(({ data }) => {
return data.map(each => each[1])
})
.then(gdpData => {
d3.select('svg')
.selectAll('rect')
.data(gdpData)
.enter()
.append('rect')
.attr('class', 'bar') \\ Here the class is applied
.attr('x', (d, i) => i * 3)
.attr('y', (d, i) => 400 - (d / 50))
.style('height', (d) => d / 50)
.style('width', 2)
.style('color', 'white')
.style('fill', 'steelblue')
});
CSS
.bar:hover {
fill: 'red'
}
I'm wondering if it something to do with the fact the bar is being rendered within the d3.json function maybe?
Thanks for reading.
Upvotes: 1
Views: 1044
Reputation: 7403
Here is how this type of problem can be debugged.
In the developer console of the web browser, it is possible to inspect the applicable css when the rectangles are being hovered.
Here is how to do it in Firefox, Chromium and the other browsers most likely have the equivalent feature.
Right-click on a rectangle in the DOM inspector, and activate Change pseudo-class \ Hover
:
This updates the layout panel, and a warning informs about a problem with the CSS rule:
Invalid property value.
This is because there should not be quotes in the CSS color definition.
.bar:hover {
fill: red;
}
When you update the CSS as above, you notice that the red color is still not applied. This is because the inline style has precedence over the style defined in the stylesheet.
Inline styles added to an element (e.g., style="font-weight: bold;") always overwrite any styles in external stylesheets, and thus can be thought of as having the highest specificity.
Source: How is specificity calculated.
An easy and clean solution is to move the steelblue
fill definition to the stylesheet:
.bar {
fill: steelblue;
}
.bar:hover {
fill: red;
}
Upvotes: 4