Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Jacqui Purdy
Jacqui Purdy
12,512 Points

How do you use jQuery to replace an image on hover?

I'm trying to replace an image with another image on hover, but using the code below, it doesn't seem to be recognizing my second image:

    $("img.image-1").mouseenter(function () {
        $(this).replaceWith($('<img src="~/Content/images/prosecutor_tile_b.jpg">'));
    });

2 Answers

Your code looks fine, it's the path to the image that's the issue. You should use a relative path instead of the home directory shortcut (~). For this example it would probably just be "images/prosecutor_tile_b.jpg".

Jacqui Purdy
Jacqui Purdy
12,512 Points

I figured it was something with the image... I'm working in Visual Studio which complicates things with the path. The exact same path I have in my script code works fine when loading the original image within the body earlier on the page (tile_a.jpg - which I want to change on hover to tile_b.jpg). Is there a reason that the image would be recognized within the body but not in the script tags at the bottom? (Thank you for your response!)

Jacqui Purdy
Jacqui Purdy
12,512 Points

We figured it out! Geoff Parsons you were correct about the path being the issue. Some of the developers I work with who are more familiar with visual studio than I am showed me how to write the image path in a way that solved the problem. (it needed to be absolute vs. relative) :

$("img.image-1").mouseenter(function () {
    $(this).attr('src', '@Url.Content("~/content/images/prosecutor_tile_b.jpg")');
});