Search code examples
jqueryhoverfaderollover

jquery thumbnail gallery - hover/fade


I have been struggling to get an answer to this... I have a series of thumbnails, and when I roll over them I would like the main image (in a separate div) to change to that of the thumbnail that is rolled on. I am new to programming however I am happy with the basic functionality I get with the following code:

$(document).ready(function() {
    var originalimg = $('.mainImage').attr('src');
    $(".subImage").hover(function() {
        var currentimg = $(this).attr('src');
        $('.mainImage').attr('src', currentimg);
    }, function() {
        $('.mainImage').attr('src', originalimg);
    });
});​

What I would ideally like is to add some fade in/out effect. I am sure there is a much better way of achieving this, but if someone could just change my code above to include some fade, I would really appreciate it. thanks all!


Solution

  • This should prevent any flicker or queue build up:

    var originalimg = $('.mainImage').attr('src');
    $(".subImage").hover(function() {
        var currentimg = $(this).attr('src');
        $('.mainImage').fadeOut(function() {
            $('.mainImage').attr('src', currentimg).fadeIn();
        });
    }, function() {
        $('.mainImage').fadeOut(function() {
            $('.mainImage').attr('src', originalimg).fadeIn();
        })
    });​
    

    jsFiddle example.