Context: Im trying to replace an image on mouseover, and return to original on mouseout. WHen i use the original link of the image src, it works. But my problem is that i will have multiple sections of this. I know i can make it work by making a script on each original src and input the image link there, but is there a way to make it return to original img src without adding the hard link of the img?
<div class="col-12 text-center">
<h3>TITLE</h3>
<div class="name-wrapper">
<span id="name1" class="some-name opacity-0">Name 1</span>
<span id="name2" class="some-name opacity-0">Name 2</span>
</div>
</div>
<div class="col-12">
<div class="img-set">
<img src="images/2023/some-img.jpg" alt="Some Image" />
</div>
<div class="hotspots">
<a href="#" data-src="images/2023/some-img2.jpg" data-target="name1">test1</a>
<a href="#" data-src="images/2023/some-img3.jpg" data-target="name2">test2</a>
</div>
</div>
$(".hotspots a").mouseover( function() {
var value = $(this).attr('data-src');
$(".img-set img").attr("src", value);
var target = $(this).data("target");
var targetName = document.getElementById(target);
if($(targetName).attr('id') == target) {
$("#" + target).removeClass("opacity-0");
}
})
$(".hotspots a").mouseout( function() {
$( '.img-set img' ).attr("src","images/2023/some-img.jpg");
var target = $(this).data("target");
var targetName = document.getElementById(target);
if($(targetName).attr('id') == target) {
$("#" + target).addClass("opacity-0");
}
});
How can i make it so that instead of putting in the actuall src, it would be original src instead.
So i tried with this and the whole thing doesnt work anymore
$(document).ready(function() {
var original = document.getElementsByClassName(".img-set img").getAttribute("src");
$(".hotspots a").mouseover( function() {
var value = $(this).attr('data-src');
$(".img-set img").attr("src", value);
var target = $(this).data("target");
var targetName = document.getElementById(target);
if($(targetName).attr('id') == target) {
$("#" + target).removeClass("opacity-0");
}
})
$(".hotspots a").mouseout( function() {
$( '.img-set img' ).attr("src", original);
var target = $(this).data("target");
var targetName = document.getElementById(target);
if($(targetName).attr('id') == target) {
$("#" + target).addClass("opacity-0");
}
});
})
3
Answers
The issue is that you called
which will not match the element you actually want. (You get null)
Instead use
or
You can just use jQuery instead of using javascript to select the original image src.
A bit left field but… There is a way to do this using css only using the
:has()
pseudo class. Put both images in your mark up and then toggle the display mode on the :hover selector.The only caveat is that this isn’t supported in firefox at the moment or some older browsers.
Here’s a good video by Kevin Powell on :has() that I hope explains things.
Marked up code below: