I am using d3.js to add and remove classes to a selection of elements on mouseOver() and mouseOut() events. I'd like to make the class "isHovered" and make the values of the attributes I'm changing to be relative to the element's current value. Something like this:
function handleMouseOver(d, i) {
d3.selectAll('.classToSelect')
.classed('isHovered', 'true');
};
function handleMouseOut(d, i) {
d3.selectAll('.classToSelect')
.classed('isHovered', 'false');
};
and make the isHovered class change the elements size/color:
.isHovered {
height:height*1.5;
width:width*1.5;
background-color:yellow;
}
This adds the class, but doesn't actually make any changes to the elements attributes, except its classList. I'm trying to assign and unassigned the "isHovered" class, rather than having to store the pre-hovered size/color, and manually update them, and then manually revert back to them afterwards, which I don't think is possible since these elements are sized dynamically by d3.js scaling data:
So, can I make these newly added class changes actually take effect, and can the effect be relative to an element's properties' current values?
Alternatively:
Is it possible to access the element's width:svgAnimatedWidth and Height:svgAnimatedHeight properties & values directly, so that I can change them and revert them back manually? How?
There are various ways of altering the height/width on hover.
This snippet uses CSS variables to set the initial height and width in a class and then uses them to calculate new values in the isHovered class.
const div = document.querySelector('div');
div.addEventListener('mouseover', function() {
div.classList.add('isHovered');
});
div.addEventListener('mouseout', function() {
div.classList.remove('isHovered');
});
div {
--h: 100;
--w: 200;
height: calc(var(--h) * 1px);
width: calc(var(--w) * 1px);
background-color: blue;
}
.isHovered {
--hhovered: calc(var(--h) * 1.5);
--whovered: calc(var(--w) * 1.5);
height: calc(var(--hhovered) * 1px);
width: calc(var(--whovered) * 1px);
background-color: yellow;
}
<div></div>
It is also possible to alter CSS variables using JS style.setProperty and to read them using style.getPropertyValue.
As a complete alternative if the aim is just to increase the height and width of an element on hover then the CSS transform scale could be used.
div {
height: 100px;
width: 200px;
background-color: blue;
}
div:hover {
transform: scale(1.5);
background-color: yellow;
}
<div></div>
This has the advantage (or disadvantage, depending on what effect is actually required) of not affecting surrounding elements' positioning.