Maanstraat
Maanstraat

Reputation: 1251

jQuery hover a link swap image

I want to do the follow, if a user hover on a link that the image will swap with a image with '-on' at the end.

But how can i get the swap thing on the image when i hover the a tag?

HTML code:

<div>
    <a href="#">
        <img src="image.jpg" alt="" />
        Here some caption
    </a>
</div>

I can not place the image urls in the header...

Upvotes: 4

Views: 18437

Answers (5)

Circle B
Circle B

Reputation: 1674

Here's a way to have the image go back to it's original state when the mouse leaves.

    $(document).ready(function($) {
    	$('img').on('mouseover', function(){
    		src = $(this).attr('src').replace('hover', 'thanks!');
    		$(this).attr('src', src);
    	})
    	$('img').on('mouseout', function(){
    		src = $(this).attr('src').replace('thanks!', 'hover');
    		$(this).attr('src', src);
    	});	
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>

<img src="http://placeholder.pics/svg/500x150/DEDEDE/555555/hover" />

Upvotes: 1

npixels
npixels

Reputation: 31

$(document).ready(function($) {
	$('img').on('mouseover', function(){
		src = $(this).attr('src').replace('.gif', '-hover.gif');
		$(this).attr('src', src);
	})
	$('img').on('mouseout', function(){
		src = $(this).attr('src').replace('-hover.gif', '.gif');
		$(this).attr('src', src);
	});	
});

Upvotes: 2

Greg
Greg

Reputation: 3568

You can use the DOM 'mouseover' event on the a tag and attach a callback to it (then inside, you'll change the image's URL)

edit, sample code:

<div>
<a id="myLink" href="#">
    <img id="myImg" src="image.jpg" alt="" />
    Here some caption
</a>
</div>

in JS:

var img = document.getElementById('myImg');
document.getElementById('myLink').onmouseover = function(){
    //manipulate the image source here.
    img.src = img.src.replace(/\.jpg/, '-on.jpg');
}

You will then need to use onmouseout to put the original image back.

Upvotes: 2

Eli
Eli

Reputation: 14827

To change src of your image just just attr:

$('img').attr("src", "image2.jpg");

You need to use hover:

$("a").hover(
function() {
    $(this).find('img').attr("src", "image2.jpg");
},
function() {
    $(this).find('img').attr("src", "image.jpg");
}
);

Upvotes: 6

hjpotter92
hjpotter92

Reputation: 80639

$(function () {
    $('a img').hover( function () {
        $(this).attr('src', $(this).attr('src').replace(/\.jpg/, '-on.jpg') );
    });
});

Read the jQuery docs on replace and attr.

Upvotes: 12

Related Questions