Search code examples
javascriptjqueryfadeinfadefadeout

FadeIn new background image Jquery


I have a div with a background image defined:

#section0{
        background-image: url("images/top_back2.jpg");
    }

I have a setTimeout function changing the background image to something else 3s later

    $("#section0").css("background-image", "url(images/top_back.jpg)");
        }, 3000);

This works fine, but I can't seem to be able to make this image fade in no matter what I try.

Any ideas would be appreciated, it just appears on screen like this and it's very jarring. I can't add CSS3 fade in to the whole element as the content inside isn't shown for the first 3 seconds, and I need it to appear.

Thanks!


Solution

  • You have to define how it fades it as well, you can use opacity to achieve this effect, followed by the transition parameter which defines the animation properties such as duration and easing.

    CSS:

    #section0{
         opacity: 0;
         transition: opacity 2s; /* Define the duration of the opacity animation */
         background-image: url("images/top_back2.jpg");
    }
    

    JavaScript (inside your setTimeout):

    $("#section0").css({
         "opacity" : 1,
         "background-image": "url(images/top_back.jpg)"
    });
    

    Here is a demo on JSFiddle with the code https://jsfiddle.net/wtbmdaxc/

    Enjoy :)


    Update:

    To avoid the text to being covered, there are two ways to do it, either you separate your background image into another DIV and apply the opacity to that new DIV or you create a pseudo-element. Both of which have already been answered on SO before.

    Let's try the first method, how it will work in your case

    HTML:

    <div id="section0">
      Example test. Lorem ipsum dolor sit amet.
      <div id="bg-opacity"></div>
    </div>
    

    CSS:

    #section0{
    }
    
    #section0 #bg-opacity{
         position: absolute; /* Force this layer to appear at the top left of the div */
         top: 0;
         left: 0;
         z-index: -1; /* Makes the image appear in the back and not covering the texts */
         opacity: 0;
         transition: opacity 2s; /* Define the duration of the opacity animation */
         height: 500px;
         width: 500px;
         background-image: url("https://media.giphy.com/media/tIeCLkB8geYtW/giphy.gif");
    }
    

    JavaScript:

    setTimeout(function(){ 
      $("#bg-opacity").css({
           "opacity" : 1,
           "background-image": "url(https://media.giphy.com/media/tIeCLkB8geYtW/giphy.gif)"
      });
    }, 300);
    

    And a new demo on JSFiddle: https://jsfiddle.net/zr7Lf0m5/