JQuery hover link to swap image

I want to do the following if the user had a link to a link that the image will exchange with the image with "-on" at the end.

But how can I get the exchange item on the image when I hang the tag?

HTML code:

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

I can't put image urls in the header ...

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

Read jQuery docs on replace and attr .

+11
source

To change the src your image simply 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"); } ); 
+6
source

You can use the DOM "mouseover" event in the tag and attach a callback to it (then inside you change the image URL)

edit example 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'); } 

Then you will need to use onmouseout to return the original image.

+2
source

 $(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); }); }); 
+2
source

All Articles