smack-a-bro smack-a-bro - 1 month ago 7x
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(){



default_image = $("#image").attr("src");


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


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="" />

<ul id="list">
    <a class="preview" href="#" rel="">Computer</a>
    <a class="preview" href="#" rel="">Mac</a>
    <a class="preview" href="#" rel="">Laptop</a>