JD Isaacks
JD Isaacks

Reputation: 57974

transition background-image/css change on hover?

I have a thumb nail inside another div, when the thumbnail is hovered I want the parent div to fade/transition to the background of the thumbnail, then fade back to the original image after hover.

I have this so far which changes the parent background to that of the thumbnail and back but with no transition.

$(document).ready(function() {

    var originalBG;
    var hoverBG;
    $(".alt-img").hover(
        function () {
            originalBG = $(this).parent().css('backgroundImage');
            hoverBG = $(this).css('backgroundImage');
            $(this).parent().css('backgroundImage',hoverBG);
        }, 
        function () {
            $(this).parent().css('backgroundImage',originalBG);
        }
    );

});

Upvotes: 1

Views: 1281

Answers (2)

JD Isaacks
JD Isaacks

Reputation: 57974

Based on what jAndy suggested I was able to come up with this:

$(document).ready(function() {

    var originalBG;
    var hoverBG;
    $(".alt-img").hover(
        function () {
            originalBG = $(this).parent().css('background-image');
            hoverBG = $(this).css('background-image');
            //$(this).parent().css('background-image',hoverBG);
            $(this).parent().animate({opacity: 0.1}, 200,
                function () {
                    $(this).css('background-image',hoverBG);
                    $(this).animate({opacity: 1}, 200);
                }
            );
        }, 
        function () {
            //$(this).parent().css('background-image',originalBG);
            $(this).parent().animate({opacity: 0.1}, 200,
                function () {
                    $(this).css('background-image',originalBG);
                    $(this).animate({opacity: 1}, 200);
                }
            );
        }
    );

});

Its not a true cross-fade because it fades the original image out, then fades the new image in. But a close compromise.

Upvotes: 0

jAndy
jAndy

Reputation: 235972

There is no 'build-in' solution for fading in/out a backgroundImage, but you may play around with chaining animate()

.animate({opacity: 0.5}, 1000)

for instance. Or use .css() aswell to just set a new opacity level.

Upvotes: 1

Related Questions