Reputation: 1927
I'm somewhat new to jquery and I have this working function that swaps images on the hover of a list element. I am trying to add a fadeOut and fadeIn but its not working. The image fades out, but it doesn't get the correct path for the new image.
This is the working script:
$(document).ready(function() {
var path = 'images/';
$('.menu-child').hover(function() {
var newimage = $(this).attr('data-path') + '.jpg';
$('.swap > img').attr('src', path + newimage)
});
});
This is what I tried for fade effect (and a couple of variations, none of which I could get to work):
$(document).ready(function() {
var path = 'images/';
$('.menu-child').hover(function() {
var newimage = $('.menu-child').attr('data-path') + '.jpg';
$('.swap > img').fadeOut(function() {
$('.swap > img').attr('src', path + newimage).fadenIn();
});
});
});
HTML:
<section class="submenuWrapper">
<ul class="twinsub">
<li class="twinmultisub twinleft">
<ul>
<li class="menu-child" data-path="menu-interior"><a href="#"><span>Interior Painting</span></a></li>
<li class="menu-child" data-path="menu-exterior"><a href="#"><span>Exterior Painting</span></a></li>
</ul>
</li>
<li class="twinmultisub twinimg">
<section class="swap">
<img src="images/menu-exterior.jpg" />
</section>
</li>
</ul>
</section>
Upvotes: 1
Views: 295
Reputation: 831
There we a couple of things.
Try this:
$(document).ready(function() {
var path = 'images/';
$('.menu-child').hover(function() {
var newimage = $(this).attr('data-path') + '.jpg';
$('.swap > img').fadeOut(function() {
$(this).attr('src', path + newimage).fadeIn();
});
});
});
Working Example: https://jsfiddle.net/sabrick/fudLgqxs/3/
You'll probably be able to figure out why it works now on your own, but let me know if you'd like any additional details.
Upvotes: 1
Reputation: 879
Here is a sample with appropriate comments
$(document).ready(function() {
var path = 'images/';
$('.menu-child').hover(function() {
var newimage = $(this).attr('data-path') + '.jpg';
if(newimage != (path + $('.swap > img').attr('src'))){
/*if the current image being displayed is not the same
as the data-path of the hovered element.
This prevents it from running even when the image should
not be changing
*/
$('.swap > img').fadeOut(0);
//first fade out the current image
$('.swap > img').attr('src', path + newimage);
//then change the path when it is not visible
$('.swap > img').fadeIn(500);
//then fade in the new image with the new path
}
});
});
Upvotes: 0