Dan Davies
Dan Davies

Reputation: 163

Multiple image swap on hover

Hi Guys I have been looking around for this answer and my head hurts.

I have a page with team members' images and I want it to be such that when you hover over each image, another image of that team member appears. Simple, well I can do it with css for each member but was wondering if there is a way using query so that it can be done by the name of the files, e.g. dan.jp and dan-hover.jpg.

Thanks

Dan

EDIT: I would also like it to be such that when you hover off the image, the original image replaces the other image so the new image only appears while the mouse is hovering on the image.

Upvotes: 1

Views: 3545

Answers (3)

Teneff
Teneff

Reputation: 32148

I guess you need something like this:

$('img').hover(function(){
    $(this).data('on',
        $(this).attr('src')).attr('src', $(this).data('on').replace(/(\.\w+)$/, "-hover$1")
    );
},function(){
    $(this).attr('src', $(this).data('on'));
});

Edit: to change only specific images you can (for example) do this:

put all the desired images in a container

<div class="desired_images">
    <img src="..." />
    ...
</div>

and then change the jQuery selector to:

$('.desired_images img') ...

Upvotes: 1

aziz punjani
aziz punjani

Reputation: 25766

Just user .hover

$('#images img').hover(
     $this = $(this); 
     function(){
         $this.data('src', $this.attr('src') );   // store the current image url on hover
         var img_name_extension = $this.data('src').split('.'); 
         var hover_image = img_name_extension[0] + '-hover.' + img_name_extension[1]; 
         $this.attr('src', hover_image); 
     }, 
     function(){ 
         $this.attr('src' , $this.data('src') ); // revert back to the old image url on hover out
     }
 ); 

Upvotes: 1

ZolaKt
ZolaKt

Reputation: 4721

There are really a lot of topics and examples on this subject.

For example, look here:
Change the image source on rollover using jQuery

Upvotes: 0

Related Questions