Reputation:
I am attempting to use jQuery to hover over an image while it changes the other. I have that part done, the part I don't understand is when I hover over the image and then move the mouse off of it, how do I get the original image to come back? Any help would be greatly appreciated.
Here is what I have so far:
$(document).ready(function(){
$("#04").hover(function(){
$("#imgBig").attr("src", "imgLab10/04.jpg");
});
});
Upvotes: 1
Views: 108
Reputation: 4401
JQuery .hover() method takes two function parameters. One is onMouseover event and the second is onMouseout event.
.hover(handlerIn, handlerOut) handlerIn Type: Function( Event eventObject ) A function to execute when the mouse pointer enters the element. handlerOut Type: Function( Event eventObject ) A function to execute when the mouse pointer leaves the element.
Upvotes: -2
Reputation: 67505
The you have to use it like :
$( "#04" ).hover(
function() {
//When the mouse enter
$("#imgBig").attr("src", "imgLab10/04.jpg");
}, function() {
//When the mouse out
$("#imgBig").attr("src", "imgLab10/OriginalImage.jpg");
}
);
Hope this helps.
Upvotes: 0
Reputation: 54618
I'm not a fan of changing the img source because you can have lag or disconnect issues then your alternative image may now show. This can also be done without jQuery altogether.
.img-swap{
width: 100px;
height: 100px;
}
.img-swap .img-swap-alt{
display: none;
}
.img-swap:hover .img-swap-alt{
display: block;
}
.img-swap:hover .img-swap-def{
display: none;
}
<div class="img-swap">
<img class="img-swap-def" src="http://lorempixel.com/output/abstract-q-c-300-300-10.jpg"/>
<img class="img-swap-alt" src="http://lorempixel.com/output/food-q-c-300-300-1.jpg" />
</div
Upvotes: 2
Reputation: 51917
I recommend you use .prop()
instead of .attr()
because it will eventually become deprecated.
If you want to change the image back, you need to use .mouseenter()
and mouseleave()
$(document).ready(function() {
$("#04").mouseenter(function() {
$("#imgBig").prop("src", "imgLab10/04.jpg");
});
$("#04").mouseleave(function() {
$("#imgBig").prop("src", "orignalPath");
});
});
I think this makes the code easier to understand because you're explicitly coding for both events, but that's just my opinion and .hover()
also works well.
Upvotes: 0
Reputation: 2289
.hover()
accepts two callbacks, one for hoverIn
and one for hoverOut
.
So you could do something like
$(document).ready(function(){
$("#04").hover(
function(){
$("#imgBig").attr("src", "imgLab10/04.jpg");
},
function() {
$("#imgBig").attr("src", "oldImg.jpg");
}
);
});
Upvotes: 2