Update the picture dynamically when hovering

Is there a way to change an image randomly when hovering over it? The hover effect is working fine, but the image does not revert back when the mouse moves out. Any suggestions on how to fix this?

var arr = ["020", "053", "306", "035", "930"];

function getRandomImage() {
  var index = Math.floor(Math.random() * arr.length);

  return arr[index];

}

$(function(){
$(".size-woocommerce_thumbnail").hover(function(){
    var image = getRandomImage();
    $(this).attr("srcset", function(index, attr){
        return attr.replace("070", image);
    });
    $(this).attr("src", function(index, attr){
        return attr.replace("070", image);
    });
}, function(){
    $(this).attr("srcset", function(index, attr){
        return attr.replace(image, "070");
    });
    $(this).attr("src", function(index, attr){
        return attr.replace(image, "070");
    });
});
});

Answer №1

Is there any error displayed on the console? It seems that the scope of var image = getRandomImage(); is within the callback function triggered on hover, causing image to be undefined when the second function runs on mouseout.

One solution could be to store the value of image in a data-* attribute and retrieve it on mouseout. Here's an example:

$(".size-woocommerce_thumbnail").hover(function(){
  var $this = $(this);
  var image = getRandomImage();
  $this.attr("srcset", function(index, attr){
    return attr.replace("070", image);
  });
  $this.attr("src", function(index, attr){
    return attr.replace("070", image);
  });
  $this.data('image', image);
}, function(){
  var $this = $(this);
  var image = $this.data('image');
  $this.attr("srcset", function(index, attr){
      return attr.replace(image, "070");
  });
  $this.attr("src", function(index, attr){
      return attr.replace(image, "070");
  });
});

Additionally, consider saving the value of $(this) instead of calling it repeatedly to prevent recreating the jQuery object. Chaining functions can also help optimize your code.

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

Tips on positioning content beneath a fixed header or navigation bar when viewed in a web browser

Hi, I'm having an issue with creating a fixed header using HTML and CSS. When I set my header to be in a fixed position, it covers up the content below it. I want the content to be positioned under the header when the page is loaded. Additionally, I&a ...

href not functioning properly on subsequent clicks, whereas onclick remains active

I'm experiencing an issue with a button that opens a modal. When clicking the button, it's supposed to open a new page in the modal and also make an API call for processing before loading the new page. <a class="btn btn-primary" type='b ...

Oh no, there seems to be an issue with accessing the 'map' property in REACT JS. It appears to

Upon attempting to delete an item, I encountered an error message stating "cannot read notes, property of undefined". Despite this issue, the map function seems to be functioning as expected. It is my belief that there may be an error within the filter fun ...

Do not fulfill the promise until all the images have finished loading

Below is the intended process: Iterate through a collection of img tags Retrieve each tag's src URL Convert it to a base64 encoded string using an HTML 5 canvas Once all images have been converted, resolve the promise and call the callback function ...

How to implement saving TypeScript Map() in Firebase Cloud Functions?

I am currently developing a Firebase Cloud Functions application using TypeScript that is designed to save an instance of Map() to Cloud Firestore. The map consists of user IDs as keys and objects with 2 simple attributes as values. Due to the dynamic natu ...

Obtaining the text content of a <div> element when clicked using Selenium

I am trying to extract the email address from the code snippet below, but I am unsure of how to do it. Any assistance would be greatly appreciated! <div class="taLnk hvrIE6 fl" onclick="ta.trackEventOnPage('Listing', 'Email', 774169 ...

An undefined variable in Angular 2's evaluation

I am currently working with the following code: @ViewChild('MondayPicker') MondayPicker; @ViewChild('TuesdayPicker') TuesdayPicker; @ViewChild('WednesdayPicker') WednesdayPicker; @ViewChild('ThursdayPicker') Thursda ...

Discovering the initial element with a data attribute above zero using JQuery

I am working with a set of divs that have the class .item-wrap. At the moment, I am able to select the first div using this code snippet: $(".item-wrap:first").trigger( "click" ); Each .item-wrap element comes with a data-amount attribute. My challenge ...

Having difficulty with pagination within a callback function

I have been attempting to paginate in a call to a callback function, but I am encountering an error on the second call. Here is what my function does: let content = '' let size = 100 let from = 1 function result(size, from, callback) { ap ...

Oops! It seems like there's a problem with reading the 'strEmail' property of undefined. Do you have any ideas on how to fix this issue

Currently, I am working with Express.js to create a straightforward login post request. Here is the code snippet: app.post("/login", (req, res) => { res.send( { isUserRegistered: userLogin(req.body.strEmail, req.body.strPassword), ...

Error: The property 'children' is not found in type '{ children?: ReactNode; }'

I have been working on implementing the search bar feature from the provided link. Despite my efforts to match the types correctly, I keep encountering a TypeScript error. Homepage.tsx const [searchQuery, setSearchQuery] = useState(query || '' ...

Tips for inserting information into data tables

Let me begin by outlining the process I am undertaking. I interact with a remote JSON API to retrieve data, perform some basic operations on it, and ultimately produce a data row consisting of three variables: Date, name, and message (think of an IRC chat ...

JQuery enthusiast seeks cheerful clicker for callback upon event binding

Incorporating a complex functionality into a click event is proving to be challenging $(someSelector)).bind('click', someFunction(a,b,c)); function somefunction(a,b,c) { return function() { // dive into complexity $(anotherS ...

Is there a way to determine in FireBug the specific JavaScript code being received from the server following an Ajax request?

Within my HTML code, I am transmitting a dollar amount to the server in order to convert its currency within the application. Is there a way for me to use FireBug to track and view the JavaScript that is being received from the server following this Ajax ...

Challenges with managing controllers within Directives

Currently, I am in the process of updating some code within a personal project that utilizes Angular to adhere to best practices. I have come across suggestions that the future direction of Angular involves incorporating a significant amount of functionali ...

Encountering the "TypeError: document.getElementById(...) is null" error message while utilizing react.js in conjunction with chart.js

I am encountering an issue while using react and chart.js together to create a bar chart. The problem lies in the fact that chart.js requires the use of canvas tags, and we need to locate this tag and insert the bar chart within it using the traditional do ...

Module '../../third_party/github.com/chalk/supports-color' not found in the directory

Within my tutoring-frontend-main project folder There is a file named package.json { "name": "app-frontend", "version": "0.0.0", "license": "MIT", "scripts": { "ng": "ng", "start": "ng serve", "build": "ng build --prod", "test": "n ...

Tips for confirming a date format within an Angular application

Recently, I've been diving into the world of Angular Validations to ensure pattern matching and field requirements are met in my projects. Despite finding numerous resources online on how to implement this feature, I've encountered some challenge ...

What causes a standard React component with a default render prop to not pass PropTypes validation successfully?

I'm currently working on a React component with a render-prop that has a generic type. To improve usability, I want to set a default value for the render-prop. The code is functioning correctly, but during type-checking, I encountered a warning regard ...

Can jQuery script be used within a WordPress page for inline execution?

Can jQuery be executed in the middle of a page (inline)? I attempted to run the following code within a custom WordPress template.... <script type="text/javascript"> jQuery(document).ready( function() { jQuery(".upb_row_bg").css("filter","blur(30 ...