It is not possible to change an image src
attribute on hover an an element using only CSS.
However, it is possible to change the background-image
property of an element on hover of another element in CSS. If you're willing to use a <div>
element with a background instead of an <img>
element, this will give you the same effect.
This can be done with the general sibling combinator (~
), as is seen in the following:
.image {
height: 100px;
width: 100px;
background-image: url('http://via.placeholder.com/100');
}
.green:hover ~ .image {
background-image: url('http://via.placeholder.com/100/00ff00');
}
.red:hover ~ .image {
background-image: url('http://via.placeholder.com/100/ff0000');
}
.orange:hover ~ .image {
background-image: url('http://via.placeholder.com/100/ffa500');
}
<a class="template-image" href="/template-1978944/editor">
<div class="green">Green</div>
<div class="red">Red</div>
<div class="orange">Orange</div>
<div class="image"></div>
</a>
If you cannot update the HTML, you'll be forced to rely on a JavaScript solution. This can be done by first selecting the image with getElementsByTagName()
, and then adding a function that updates the .src
of the image during the .onmouseover
of the other elements.
This can be seen in the following:
let image = document.getElementsByTagName('img')[0];
document.getElementsByClassName('green')[0].onmouseover = function() {
image.src = 'http://via.placeholder.com/100/00ff00';
};
document.getElementsByClassName('red')[0].onmouseover = function() {
image.src = 'http://via.placeholder.com/100/ff0000';
};
document.getElementsByClassName('orange')[0].onmouseover = function() {
image.src = 'http://via.placeholder.com/100/ffa500';
};
<a class="template-image" href="/template-1978944/editor">
<div class="green">Green</div>
<div class="red">Red</div>
<div class="orange">Orange</div>
<img src="http://via.placeholder.com/100">
</a>