Using Javascript to restore image to its original state in OpenCart 2.3

I recently created a JavaScript function that successfully replaces the main image on a product page with a different image when clicked. While this feature is functioning perfectly, I am struggling to make the original image return once the mouse leaves the area. My attempts at implementing this functionality have been unsuccessful.

In addition, I am looking to incorporate a slight delay into the process so that there is a brief pause before reverting back to the original image after the mouse is removed. These modifications are specifically for use 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();

});

If anyone can assist me in writing the necessary additional code to achieve this desired behavior, I would greatly appreciate it. Thus far, my own attempts have been met with no success.

Answer №1

To achieve the desired outcome, utilize JavaScript.

(function() {
  var img, defaultImage, preview, i, hnd;
  img = document.getElementById("image"); // Obtain the image element.
  defaultImage = img.src; // Assign the image src attribute to the defaultImage variable.
  preview = document.querySelectorAll(".preview"); // Retrieve elements with the CSS selector as «.preview».

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

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

    });
  }
})();
#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>

Answer №2

Here is a suggested code snippet:

$("a.hover").mouseout(function(){
setTimeout(function () {
        var default_img = $("#defaultImg").attr("src");
$("#img").attr("src", default_img);   
    }, 3000);
 });
  

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Merging a VUE project and a .NET framework project to unleash their full potential

Currently, I am working on a project that involves using VUE for the client side and .net framework for the server side. However, these two components are hosted as separate projects, requiring me to open different ports during development. I am aware tha ...

Tips for implementing validation in AngularJS

Could someone help me with AngularJS validation? I'm new to it and trying to make sure everything is correct. var app=angular.module('myApp',[]) app.controller('myController',function($scope){ $scope.clickMe = function(){ if($(& ...

Verify if any choices are available before displaying the div block

I need to determine if there is a specific option selected in a dropdown menu, and then display a div if the option exists, otherwise hide it. I'm not just checking the currently selected option, but all available options. if (jQuery(".sd select opti ...

Tips for locating a file using javascript

My application scans a folder and displays all folders and HTML files inside it in a dropdown menu. It also shows any HTML files inside an iframe. There is one file named "highlighted.html" that should not appear in the dropdown menu, but if it exists in t ...

JSON is often portrayed as a singular value

I am attempting to save settings in my SQL Database and then restore them using ajax and php. However, I am encountering an issue where only one long JSON Value is returned instead of three separate values for each setting. Settings: {"setting1":"true","se ...

Circular movement in ThreeJS within a specified duration

I am currently working on creating a circular motion for an object within a set time frame. This project involves designing a clock with smooth motion. Instead of simply updating the position to fixed coordinates every time .getSeconds() changes, I aim t ...

Best practice for detecting external modifications to an ngModel within a directive

I've been working on creating a directive that can take input from two sources and merge them into one. To achieve this, I'm monitoring changes in both inputs and updating the combined value in the ngModel of my directive. However, there's ...

What makes React stand out as a server side rendering technology when compared to Angular?

While delving into the world of ReactJs, I discovered a unique comparison between its rendering aspect and AngularJs. Interestingly, some refer to ReactJs as a server-side rendering technology. This revelation has truly caught me off guard! To explore fu ...

View the picture directly on this page

Currently, I am in the process of creating a gallery and I would like the images to open on top of everything in their original size when clicked by the user. My expertise lies in HTML and CSS at the moment, but I am open to learning JavaScript and jQuery ...

Can you verify that the client's date and time locale are accurate in JavaScript before proceeding with processing?

For my application, I am seeking the current locale datetime. However, before retrieving the date, it is crucial to verify that the local date and time are accurate. If the user has adjusted the date and time incorrectly on their machine, I must prompt a ...

Is there a way to customize the Webpack output to incorporate specific options solely for a particular bundle?

Currently, I am using Webpack 4 to build multiple bundles. My requirement is to add the output options libraryTarget and library for a single bundle only. The default configuration looks like this: output: { path: path.resolve(__dirname, 'dist/j ...

Static addition of the Button to the parent div is crucial for seamless

Introduction: My current project involves managing interns, and I am focusing on the employee side. Employees have the ability to add, edit, and delete interns through modal popups. Strategy: To avoid unnecessary repetition of code, I decided to create a ...

Encountered an issue loading resource: net::ERR_BLOCKED_BY_CLIENT while attempting to access NuxtJS API

After deploying my NuxtJS 2 app on Vercel and adding serverMiddleware to include an api folder in the nuxt.config.js file, everything was working smoothly. However, when I tried making an api call on my preview environment, I encountered an error: POST htt ...

Material-UI Autocomplete can only save and display one specific property of an object at a time

Can someone help me with implementing Autocomplete from Material-UI? I want to store only a specific property value and not the entire object. For example, let's say I want to store the property Value, but it could be any other property as well. con ...

JavaScript code encounters an error stating "TypeError: n is undefined"

I recently crafted a JavaScript script to accomplish a specific task, and overall it was working smoothly. However, as I attempted to simplify the code for a demonstration here on this platform, I encountered two issues. Unfortunately, during this 're ...

Submitting requests in Node.js Express

Can a request for a specific route be dropped using Node.js and express? For example, not returning an HTTP status or any headers, but simply closing the connection? app.get('/drop', function(req, res) { //What is the method to drop the requ ...

Tips for containing a range slider within a div element in a flexbox container

I am currently using Javascript to generate a grid of images, and I want to include a range slider at the bottom of one of the images. Here is a simplified version of my code using flex-container: <style> .flex-container { display: flex; fle ...

Identifying button clicks using selenium-wire in Python

Is there a way to use selenium-wire in python to capture a full screenshot of a web page and save it as a png file after clicking the submit button? Despite seeing a popup message saying "taking screenshot!!", the actual screenshot file is not being saved ...

After a duration of 4 minutes, an ERR_EMPTY_RESPONSE is thrown in response to the

My angular 5 node app involves sending a request to the server and waiting for a response. There are instances where the response takes around 5-6 minutes to arrive. However, an ERR_EMPTY_RESPONSE error is triggered by the http method after just 4 minutes ...

Instruments for crafting an application compatible with a wide range of web browsers

Currently tackling various browser challenges. I find myself wondering whether it's achievable to create an application that is compatible with all browsers, or at least the majority. Should it be a web application? Any recommendations on frameworks a ...