1
votes

I'm trying to figure out if it's possible to fadeIn a background image of a div, I currently have a function which shows a background image of the relevant div on hover, but the show / hide is a bit harsh I'd like it to fade In / Out instead, can't figure out how to do so though.

Here's my code:

jQuery(document).ready(function(){
    jQuery(".thumbnail").hover(function(){
        var imgurl = jQuery(this).data("hoverimage");
        jQuery(this).css("background-image", "url(" + imgurl + ")");
    }, function(){
        jQuery(this).css("background-image", "");
    });
});

This function simply shows the background image on mouseenter and hides it again on mouseleave, is it at all possible to fadeIn when hovering over the relevant div instead and fadeOut when leaving the div?

2
You can't fade in a background-image. You need to put a div behind it.Mooseman

2 Answers

0
votes

You can't fade in the background image only. What you can do is fade in an element with an identical offset that has the background image (or is even an image element itself). Just add another element with position: fixed (or absolute if the parent is relative) that has the image you desire.

$("#hasbg").append($("<div>").css({
    position: 'fixed',
    top: $("#hasbg").offset().top,
    left: $("#hasbg").offset().left,
    display: 'none',
    background: 'url(http://static.adzerk.net/Advertisers/bd294ce7ff4c43b6aad4aa4169fb819b.jpg)',
    width: $("#hasbg").width(),
    height: $("#hasbg").height()
}).attr('id', 'isbg')).on('mouseenter', function () {
    console.log($("#isbg").length);
    $("#isbg").stop().fadeIn();
}).on('mouseleave', function () {
    $("#isbg").stop().fadeOut();  
});

http://jsfiddle.net/ExplosionPIlls/nenf3/

0
votes

It is rather tricky, I was under the impression that the $(".blah").animate({}) has a color property, but thats not the case (well, atleast to my knowledge).

You might find a way out here: http://api.jquery.com/fadeIn/ (the last code snippet).