Here's a CodePen I've been working on: https://codepen.io/naregjan/pen/MBzQWp
Within this CodePen, I have an SVG container with four rectangles, two of which have gradients applied. My goal is to create a hover effect that transitions the gradient colors similar to what you see in this example.
Below is the relevant CSS code:
.red{
fill: url(#grad1);
}
.red ~ defs stop{
transition: 1s;
}
.red:hover ~ defs stop:first-child {
stop-color: #ffbbcc;
}
.red:hover ~ defs stop:last-child {
stop-color: #0000ff;
}
And here is the corresponding HTML (the rectangles are dynamically generated via JavaScript):
<svg id="sqSVG" width="500" height="500">
<rect class="square green" x="135" y="135" width="100" height="100"></rect>
<rect class="square green" x="10" y="135" width="100" height="100"></rect
<rect class="square red" x="135" y="10" width="100" height="100"></rect>
<rect class="square red" x="10" y="10" width="100" height="100"></rect>
<defs>
<linearGradient id="grad1" x1="0%" y1="0%" x2="110%" y2="110%">
<stop offset="0%" style="stop-color:#ff0000"></stop>
<stop offset="100%" style="stop-color:#ffffff"></stop>
</linearGradient>
</defs>
</svg>
I'm struggling to understand why the transition effect isn't working as expected. The stop color doesn't change on hover at all, and I've double-checked my code against the example pen I referenced. It seems like everything should be set up correctly with the parent-child relationship between the rects and defs elements... What am I missing?
Additionally, here's the function I'm using to create the squares:
function makeSquares(){
var svg = document.querySelector("#sqSVG");
var squares = [
{x : "10", y : "10", color: "red"},
{x : "135", y : "10", color: "red"},
{x : "10", y : "135", color: "green"},
{x : "135", y : "135", color: "green"}
];
squares.forEach(sq => {
var newSq = document.createElementNS("http://www.w3.org/2000/svg", 'rect');
newSq.setAttribute("class", "square " + sq.color);
newSq.setAttribute("x", sq.x);
newSq.setAttribute("y", sq.y);
newSq.setAttribute("width", "100");
newSq.setAttribute("height", "100");
svg.prepend(newSq);
});
}
However, even when I hard-code these square elements into the HTML, the hover effect still doesn't work. Any insights or assistance would be greatly appreciated.