I understand that this question has been answered before, but even after consulting those links, I am still unable to solve my problem. I want to replace my image (assets/img/social-mail.jpg) to another (assets/img/social-mail-hover.jpg), with a single class, because I have multiple images I would like to do this to. My basic thought process is this: When the class is hovered, take the ID, and replace its image with another by adding "-hover" to its image link.
HTML:
<img id="social-mail" class="box-social" src="assets/img/social-mail.jpg">
JS:
$(".box-social").hover(function(e) {
var id = $(this).attr("id");
var icon = id.split("-")[1];
var image = "img/social-" + icon + "-hover.jpg";
$(id).find("img").attr("src", image);
});
I've tested id, icon, and image; and they all give me exactly what I want. However, when I hover over the image, it still isn't being replaced. I'm not getting any errors either. What am I doing wrong? Thank you so much!
$(this)or$('#'+id)to make it a proper id selector... but use image sprites and CSS for this!.find()?thisalready refers to the current img. Don't use.attr()either:this.src = image;should do it. (Also, why are you using.split()to take the part after the hyphen when the part before the hyphen is actually part of the filename anyway? Can't you do it all with one line:this.src = "assets/img/" + this.id + "-hover.jpg";?thisis the element, you don't need tofindanything. Regardless this is a typical scenario for CSS and a single image sprite that holds all your images. No JS required.