I have created a simple way to change our product images to a secondary image as a result of hovering over the image.
When you hover out of the image it switches back to the original image.
Files containing "-1.jpg" are the original image and "-3.jpg" are the secondary image. So the code switches the image src from -1 to -3 simple enough.
My problem is that some products do not have a secondary image and when hovering over these images there currently is a visible error.
I am trying to add to my code a way to check for if the secondary image exists before changing the image. If no secondary image exists nothing will occur. If it does exist the secondary image will be swapped in.
Attached is my code and a test jsfiddle.
$(function() {
$("[src*='-1.jpg']")
.mouseover(function() {
var src = $(this).attr("src").replace("-1.jpg", "-3.jpg");
$(this).attr("src", src);
})
.mouseout(function() {
var src = $(this).attr("src").replace("-3.jpg", "-1.jpg");
$(this).attr("src", src);
});
});
Thanks!
You will have to try loading all those "secondary images".
If the image loads in a temporary variable... It exists. So add a class to the item
to have a hover
handler only for those images that have a succesfully loaded secondary.
Now... Since all those load
events will take a bit of time, you have to use a delegated event handler... The same way as if the images were dynamically added.
The nice "side effect" is all those secondary images will be "preloaded" in the browser... So your image swap should have no load delay. Two targets with one bullet!
$(function() {
// Check if -3.jpg exist for each image
// If so, add a class
$("[src*='-1.jpg']").each(function(index,item){
let temp_img = $(`<img src="${item.src.replace("-1.jpg", "-3.jpg")}">`);
temp_img.on("load", function(){
$(item).addClass("hasSecondaryImage")
})
})
// Delegated "hover" handler
$(document).on("mouseover mouseleave", ".hasSecondaryImage", fonction(e){
if (e.type === "mouseover"){
var src = $(this).attr("src").replace("-1.jpg", "-3.jpg");
$(this).attr("src", src);
}
if (e.type === "mouseleave"){
var src = $(this).attr("src").replace("-3.jpg", "-1.jpg");
$(this).attr("src", src);
}
})
})