Ranjith bhaskaran
Ranjith bhaskaran

Reputation: 25

How to change an image on mouse over?

I want to do something like this.

<a href="#" class="change-hover" >
<img src="img/image-1.jpg"  alt=""/>
<img src="img/image-2.jpg" alt=""/>
</a>
<a href="#" class="change-hover" >
<img src="img/image-3.jpg"  alt=""/>
<img src="img/image-4.jpg" alt=""/>
</a>

By default 'image-1.jpg' & img/image-3.jpg etc.. should show , On mouse over 'a' tag, hide first image and show 'image-2.jpg' & 'image-4.jpg' etc..

For reference please have a look at this Product display. http://www.thecorner.com/searchResult.asp?dept=tcshoesw&brand=25&gender=D&norewrite=1

Thanks.

Upvotes: 1

Views: 869

Answers (3)

dfsq
dfsq

Reputation: 193311

If your goal is to show the second image on hover and hide it on mouseout, showing the first, then you can use hover method like in below example.

Note, that the second image is initially hidden with CSS.

$('.change-hover').hover(function () {
    $(this).find('img').hide().last().fadeIn();
}, function () {
    $(this).find('img').hide().first().fadeIn();
});
.change-hover img {
    display: none;
}
.change-hover img:first-of-type {
    display: inherit;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<a href="#" class="change-hover">
    <img src="http://lorempixel.com/100/100/food/1"  alt=""/>
    <img src="http://lorempixel.com/100/100/food/2" alt=""/>
</a>

<a href="#" class="change-hover">
    <img src="http://lorempixel.com/100/100/food/3"  alt=""/>
    <img src="http://lorempixel.com/100/100/food/4" alt=""/>
</a>

Upvotes: 0

lante
lante

Reputation: 7346

You can do it with CSS:

.change-hover {
    float: left;
}

.change-hover img + img {
    display: none;
    position: absolute;
    top: 0;
}

.change-hover img:hover + img, .change-hover img + img:hover {
    display: block;
}

Check this fiddle.

Upvotes: 0

ntzm
ntzm

Reputation: 4821

You do not need jQuery to do this as you can do it easily using vanilla JS and even CSS.

You could save page load time by doing this (in vanilla JS):

<a href="#">
    <img src="img/image-1.jpg" onmouseover="this.src = 'img/image-2.jpg'" onmouseout="this.src = 'img/image-1.jpg'">
</a>
<a href="#">
    <img src="img/image-3.jpg" onmouseover="this.src = 'img/image-4.jpg'" onmouseout="this.src = 'img/image-3.jpg'">
</a>

Upvotes: 2

Related Questions