smack-a-bro smack-a-bro - 2 months ago 8
Javascript Question

Use Javascript to make image go back to original - OpenCart 2.3

I wrote some JS that lets me replace the main image on a product page with that a different image. This part is working great. However, I need the original image to return once the mouse leaves. I cannot get this to work.

Also, I would like to add a delay to this so that when I remove the mouse there is like a 1/4 second delay before changing back to the original image. This is all being done on the product page of OC 2.3.

this.imagePreview = function(){

$("a.preview").mouseleave(function(e){
$("#image").attr("src",default_image);
});

$("a.preview").hover(function(e){
$("#image").attr("src",this.rel);
});

$(document).ready(function(){
default_image = $("#image").attr("src");
imagePreview();

});


Can someone help me write this little bit of extra code? Everything else I've tried doesnt work.

Answer

You can get the desired result using JavaScript.

(function() {
  var img, defaultImage, preview, i, hnd;
  img = document.getElementById("image"); // Gets the image element.
  defaultImage = img.src; // Sets the image src attribute to the defaultImage variable.
  preview = document.querySelectorAll(".preview"); // Gets the elements with css selector is ┬ź.preview┬╗.

  for (i = 0; i < preview.length; i++) {
    /* Adds the mouseover event to the preview element. */
    preview[i].addEventListener("mouseover", function() {
      img.src = this.rel;
      clearTimeout(hnd); // Reset the timeout handler.
    });

    /* Adds the mouseleave event to the preview element. */
    preview[i].addEventListener("mouseleave", function() {
      hnd = setTimeout(function() {
        img.src = defaultImage;
      }, 250); // 1/4 second delay.

    });
  }
})();
#list li {
  margin: 10px;
}
<img id="image" src="https://cdn1.iconfinder.com/data/icons/technology-and-hardware-2/200/vector_66_08-32.png" />

<ul id="list">
  <li>
    <a class="preview" href="#" rel="https://cdn3.iconfinder.com/data/icons/device-icons-2/512/BT_computer-32.png">Computer</a>
  </li>
  <li>
    <a class="preview" href="#" rel="https://cdn4.iconfinder.com/data/icons/48-bubbles/48/29.Mac-32.png">Mac</a>
  </li>
  <li>
    <a class="preview" href="#" rel="https://cdn2.iconfinder.com/data/icons/crystalproject/32x32/devices/laptop.png">Laptop</a>
  </li>
</ul>

Comments