I am struggling to decide which attribute to use for implementing image swap on mouseover() and mouseout()

I have a problem using jQuery to switch between images when hovering on and off. Here's the code snippet I'm working with: HTML

<img class="commentImg" src="images/comments.png" data-swap="images/comment_hover.png" alt="">  

jQuery

$(".commentImg").hover(function() {
     var swap = $(this).attr("data-swap");
     $(this).attr('src', swap);
},
function() {
     var swap = $(this).attr("data-swap");
     $(this).removeAttr(swap);
 });  

The issue is that while the mouseover event works fine, the mouseout event doesn't trigger as expected. Can anyone assist me in resolving this?

Answer №1

In order to keep track of it, you must save the current state.

// Save the current source in an attribute
$(".commentImg").attr('data-src', function() {
  return $(this).attr('src');
})
$(".commentImg").hover(function() {
  var swap = $(this).attr("data-swap");
  $(this).attr('src', swap);
}, function() {
  var src = $(this).attr("data-src");
  $(this).attr('src', src);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<img class="commentImg" src="//placehold.it/64/ff0000" data-swap="//placehold.it/64/ff00ff" />
<img class="commentImg" src="//placehold.it/64/00ff00" data-swap="//placehold.it/64/ffff00" />
<img class="commentImg" src="//placehold.it/64/0000ff" data-swap="//placehold.it/64/00ffff" />

Answer №2

I stumbled upon an alternative solution that successfully achieves the task, especially beneficial when dealing with a plethora of images. Take a look at the following code snippet, it might be helpful for someone facing a similar challenge:

HTML

<div class="large-8 columns commentWrap">
   <img class="commentImg" src="images/comments.png" data-swap="images/comment_hover.png" alt="">
   <p class="inline_cmt">Comments (3)</p>
</div>
<div class="large-2 columns inline_rply">
   <img class="replyImg" src="images/reply.png" data-swap="images/reply_hover.png" alt="">
   <p class="dash_reply">Reply</p>
</div>
<div class="large-2 columns reportWrap">
   <img class="reportImg" src="images/report.png" data-swap="images/report_hover.png" alt="">
   <p class="inline_rep">Report</p>
</div>

jQuery

var sourceSwap = function() {
  var $this = $(this);
  var newSource = $this.data('swap');
  $this.data('swap', $this.attr('src'));
  $this.attr('src', newSource);
}

$('.commentImg').hover(sourceSwap, sourceSwap);
$('.replyImg').hover(sourceSwap, sourceSwap);
$('.reportImg').hover(sourceSwap, sourceSwap);

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

What is the method for altering the text color within a disabled input field?

Currently facing difficulty in changing the color of the text within the input field when it's disabled. I'm utilizing Material UI for this purpose. import React from "react"; import { makeStyles } from "@material-ui/core/st ...

What is the best way to generate this arc using CSS3?

What is the most effective method for creating this unique shape using CSS3? The square image should be clearly defined. We greatly appreciate any insight you can offer. EDIT: I have put in a lot of effort, but standard CSS methods are not getting me t ...

Is your animation glitching due to axis restrictions?

I decided to create my own version of the Google Maps icon using Photoshop, and now I want to replace the current image with my duplicate when the link that wraps around both is hovered over. To achieve this, I used the position: absolute property to layer ...

The persistent underline on the tooltip just won't go away

Hey there, this is my first time posting a question here so I hope I got everything right! I'm currently in the process of creating a form for a WordPress site using Bootstrap. I need to incorporate tooltips with Font Awesome icons, but for some reas ...

Searching Wikipedia using a date range and location filter: A step-by-step guide

I am attempting to replicate the functionality described by this individual using Angular on this specific Stack Overflow post The code provided is as follows: .controller('WikiQueryCtrl', ['$scope', '$http', function($scope ...

Transforming a collection of Javascript objects into a pure Javascript array

After JSON.stringify-ing my JavaScript object, the output looks like this: [ { "item_id": null, "parent_id": "none", "depth": 0, "left": "1", "right": 4 }, { "item_id": "1", "parent_id": ...

Executing Lambda functions on DynamoDB has no effect

Below is the code snippet for a Lambda function: console.log('Loading function'); var aws = require('aws-sdk'); var ddb = new aws.DynamoDB(); function retrieveUser(userid) { var query = ddb.getItem({ TableName: "Users", ...

What steps do I need to take to begin posting on NodeJS?

I am having issues creating a sample API for restaurants using the POST method. Despite launching the API and testing it in Postman, I'm not seeing any results. router.js const express = require('express'); const restaurantController = requ ...

Linking Multiple Indices in Algolia Autocomplete功能

I have configured Algolia's autocomplete.js to search through multiple indexes ('resources' and 'users'). I am trying to make the link destination different based on whether a user clicks on a 'resource' or a 'user.& ...

Retrieving text content from a file using React

I've been experiencing difficulties with my fetch function and its usage. Although I can retrieve data from the data state, it is returning a full string instead of an array that I can map. After spending a few hours tinkering with it, I just can&apos ...

Troubleshooting CSS Issues in ASP.NET Boilerplate

I am attempting to apply a CSS style to a text input similar to the one found on the CreateUser default page. However, I am encountering an issue where the blue line under the textbox does not appear when I navigate away from and then return to the page. ...

Clicking on a link to materialize will open a div containing a form for editing MySQL data

My table is fetching client information from a database, and one of the <th> tags contains an edit link with a unique id specific to each client in that row. The code snippet looks something like this: <a class="modal-trigger" href="#edit?id=< ...

Clicking on Fixed Positioning triggers a reset

When I activate the sidebar by clicking the menu button, it remains fixed in position until the first scroll. However, if I interact with the sidebar by clicking on it, the button resets and goes back to the top of the page. This issue seems to only occur ...

I'm looking to display images in a designated React component using create react app. What is the best way to accomplish

Currently in the process of revamping an older website using react. Making progress, but encountering an issue with a new component where images are not displaying. Strangely, the images appear in the main class but not within the component class. Even whe ...

Executing a function that includes showModalDialog outside of an iframe might display the incorrect page

This website structure looks like: `--main.html `--dialog.html `--folder `--iframe.html The code for each page is as follows: main.html: <html> <head> <script type="text/javascript"> function t ...

Tips for distinguishing the beginning and ending points of wrapped text in the Firefox browser

Within my work, I am utilizing a contentEditable span where I aim to position an element with position: absolute on the same line as the cursor. However, issues arise when text wrapping occurs - causing abnormal behavior at the start and end of wrapped lin ...

What steps can I take to prevent automatic redirection when submitting an input on an AJAX form in PHP?

I have encountered a strange issue with my HTML post loading dynamically inside a modal popup. I noticed that when I submit the form directly in the post, it works fine but doesn't work inside the modal :/ Every time I try to submit the form from the ...

There is a method in TypeScript called "Mapping IDs to Object Properties"

I'm currently developing a React app that features several input fields, each with its own unique id: interface IFormInput { name: string; surname: string; address: string; born: Date; etc.. } const [input, setInput] = useState< ...

Disregarding boundaries set by divisions

Trying to keep things concise here. I have a division called "the box" with a fixed width of 1200px that contains various other divisions. One of these divisions is a links bar, known as the "pink bar", which has a width of 100% and a height of 25px. My is ...

Altering calendar dates using VBA for web scraping

Seeking assistance with creating a VBA program for automatically downloading historical stock data from a website. The code I have currently works for downloading data, but I'm facing challenges in changing the date using my code. You can view the co ...