72

I have a div element with text in it and a background image, which is set via the CSS property background-image. Is it possible to fade in the background image via jQuery?

div {
  background-repeat: no-repeat;
  background-position: center;
  background-size: contain;
  background-image: url(http://upload.wikimedia.org/wikipedia/commons/8/84/Konqi_svg.svg);
  border: 1px solid #666;
  height: 10em;
}
<div>Text</div>

EDIT

I've made a fiddle exemplifying my scenario. Basically, this configures an initial background-image and a transition, and changes the background-image with jQuery. In my testing there is no animated transition between the two images.

EDIT2

My revised fiddle works!

Mosh Feu
  • 28,354
  • 16
  • 88
  • 135
aknuds1
  • 65,625
  • 67
  • 195
  • 317
  • 1
    possible duplicate of [Fading in background image with jQuery](http://stackoverflow.com/questions/1690869/fading-in-background-image-with-jquery) and about a million other questions. – JJJ Sep 06 '11 at 12:10
  • 1
    @Juhana: do those questions pertain to background images set through CSS property `background-image`? Also, do they involve changing the `background-image` through JavaScript? – aknuds1 Sep 06 '11 at 13:06
  • Yes, and in each one the answers are the same (not possible without multiple divs). – JJJ Sep 06 '11 at 13:11
  • 1
    Looking at the answer to [Fading in background image with jQuery](http://stackoverflow.com/questions/1690869/fading-in-background-image-with-jquery), it's hardly conclusive AFAICT. It only shows what can be done with jQuery `animate`. It doesn't touch on the CSS3 option either. – aknuds1 Sep 06 '11 at 13:18

10 Answers10

40

i have been searching for ages and finally i put everything together to find my solution. Folks say, you cannot fade-in/-out the background-image- id of the html-background. Thats definitely wrong as you can figure out by implementing the below mentioned demo

CSS:

html, body

height: 100%;   /* ges Hoehe der Seite -> weitere Hoehenangaben werden relativ hierzu ausgewertet */
overflow: hidden;   /*  hide scrollbars */
opacity: 1.0;
-webkit-transition: background 1.5s linear;
-moz-transition: background 1.5s linear;
-o-transition: background 1.5s linear;
-ms-transition: background 1.5s linear;
transition: background 1.5s linear;

Changing body's background-image can now easily be done using JavaScript:

switch (dummy)

case 1:

$(document.body).css({"background-image": "url("+URL_of_pic_One+")"});
waitAWhile();

case 2:
$(document.body).css({"background-image": "url("+URL_of_pic_Two+")"});
waitAWhile();
Alexander Vogt
  • 17,879
  • 13
  • 52
  • 68
user2947794
  • 409
  • 4
  • 2
  • 1
    If it can help with jQuery : `$(document).ready(function () { var img_array = ['home-corps-2.jpg', 'home-epilation.jpg', 'home-corps.jpg', 'home-ongles.jpg']; var index = 0; function fadeToNext(){ index = (index + 1) % img_array.length; $('.headline').css({'background-image':'url(public/img/'+img_array[index]+')'}); waitNext(); } function waitNext(){ setTimeout(function() { fadeToNext(); },3000); } waitNext();});` – Antoine F. Jun 29 '15 at 22:03
  • 3
    @user2947794: There is no "waitAWhile" code? Please post it if you do have it. Thank you. – dailyUnknown May 05 '16 at 22:32
  • Works well. Only criticism is that when rotating images that are of varying dimensions (portrait to landscape or vice versa) a stretching animation occurs in addition to the fade animation. – mmla Jul 05 '17 at 10:27
  • @blumonde you do know that part isn't needed right? – brandito Nov 02 '17 at 02:31
14

This is what worked for my, and its pure css


css

html {
    padding: 0;
    margin: 0;
    width: 100%;
    height: 100%;
  }

  body {
    padding: 0;
    margin: 0;
    width: 100%;
    height: 100%;
  }

  #bg {
    width: 100%;
    height: 100%;
    background: url('/image.jpg/') no-repeat center center fixed;

    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;

    -webkit-animation: myfirst 5s ; /* Chrome, Safari, Opera */
    animation: myfirst 5s ;
  }

  /* Chrome, Safari, Opera */
  @-webkit-keyframes myfirst {
    from {opacity: 0.2;}
    to {opacity: 1;}
  }

  /* Standard syntax */
  @keyframes myfirst {
    from {opacity: 0.2;}
    to {opacity: 1;}
  }

html

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
  <div id="bg">
    <!-- content here -->
  </div> <!-- end bg -->
</body>
</html>
long
  • 3,692
  • 1
  • 22
  • 38
tomter2014
  • 303
  • 3
  • 11
13

With modern browser i prefer a much lightweight approach with a bit of Js and CSS3...

transition: background 300ms ease-in 200ms;

Look at this demo:

http://codepen.io/nicolasbonnici/pen/gPVNbr

Nicolas Bonnici
  • 423
  • 4
  • 11
5

You can give opacity value as

div {opacity: 0.4;}

For IE, you can specify as

div { filter:alpha(opacity=10));}

Lower the value - Higher the transparency.

Jai Chauhan
  • 4,035
  • 3
  • 36
  • 62
Dhepthi
  • 453
  • 4
  • 11
  • 3
    The problem with `opacity` is that it affects all the children as well, not just the background image. – Flimm May 09 '16 at 19:16
4

It's not possible to do it just like that, but you can overlay an opaque div between the div with the background-image and the text and fade that one out, hence giving the appearance that the background is fading in.

thwd
  • 23,956
  • 8
  • 74
  • 108
  • It would, but you can't relay on CSS3 in a production environment. It's nice to play around though. – thwd Sep 07 '11 at 05:46
2

jquery:

 $("div").fadeTo(1000 , 1);

css

    div {
     background: url("../images/example.jpg") no-repeat center; 
    opacity:0;
    Height:100%;
    }

html

<div></div>
Kalamarico
  • 5,466
  • 22
  • 53
  • 70
1

You can fade your background-image in various ways since Firefox 4 ...

Your CSS:

.box {
    background: #CCCCCC;
    -webkit-transition: background 0.5s linear;
    -moz-transition: background 0.5s linear;
    -o-transition: background 0.5s linear;
    transition: background 0.5s linear;
    }
.box:hover {
    background: url(path/to/file.png) no-repeat #CCCCCC;
    }

Your XHTML:

<div class="box">
    Some Text …
</div>

And thats it.

yokmp
  • 145
  • 2
  • 10
1

So.. I was also looking into this matter and saw that most of the answers here are asking to fade the container element, not the actual background-image. Then a hack crossed my mind. We can give multiple background right? what if we overlay other color and make it transparent, like code below-

 background: url("//unsplash.it/500/400") rgb(255, 255, 255, 0.5) no-repeat center;

This code actually works stand alone. Try it. We gave a bg image and asked other white color with transparency on top of the image and Voila. TIP- we can give different colors and transparencies to get different filter kind of effect.

0

I know i'm late, but I found a way using jquery which works on every browser(i tested it on chrome, firefox and Ie 9)and th fore-ground elements are always displayed instead of css3 transition property.

create 2 absolute wrapper and using z-index.

First set the elements that have to be in the fore-ground with the highest z-index property value, and the other elemets(all included in the body, so: body{}) with a lower z-index property value than the fore-ground elements'one , at least of 2 number lower.

HTML part:

         <div class="wrapper" id="wrapper1"></div>
         <div class="wrapper" id="wrapper2"></div>

css part:

        .fore-groundElements{              //select all fore-ground elements
                  z-index:0;               //>=0
        }
       .wrapper{
                  background-size: cover;
                  width:100%;
                  height:100%;
                  background-size: 100% 100%;
                  position:absolute;
         }

        #wrapper1{
               z-index:-1; 
        }


        #wrapper2{
                 z-index:-2;
         }
         body{

              height:100%;
              width:100%;
              margin:0px;   
              display:cover;
              z-index:-3                          //<=-3
         }

than the javascript/jquery one:

i needed to change the background image every three second so i used a set timeout.

this is the code:

  $(document).ready(main);

  var main = function(){

             var imgPath=[imagesPath1,..,...];                 // the array in which store the image paths

             var newWrapper;                     // the wrapper to display 
             var currentWrapper;                 //the current displayed wrapper which has to be faded
             var l=2;                             // the next image index  to be displayed, it is set to 2 because the first two position of the array(first two images) start already setted up
             var imgNumber= imgPath.length;        //to know when the images are over and restart the carousel
             var currentImg;                       //the next image path to be displayed


             $('#wrapper1').css("background-image", 'url'+imgPath[0]);         //pre set the first wrapper background images
             $('#wrapper2').css("background-image", 'url'+imgPath[1]);          //pre set the first wrapper background images   

             setInterval(myfunction,3000);                //refresh the background image every three seconds

             function myfunction(){
                    if(l===imgNumber-1){               //restart the carousel if every single image has already been displayed                  
                         l=0;
                     };

             if(l%2==0||l%2==2){                    //set the wrapper that will be displaied after the fadeOut callback function
                  currentWrapper='#wrapper1';         
                  newWrapper='#wrapper2';
             }else{
                  currentWrapper='#wrapper2';
                  newWrapper='#wrapper1';
             };
             currentImg=imgPath[l];
            $(currentWrapper).fadeOut(1000,function(){               //fade out the current wrapper, so now the back-ground wrapper is fully displayed
                  $(newWrapper).css("z-index", "-1");                //move the shown wrapper in the fore-ground
                  $(currentWrapper).css("z-index","-2");             //move the hidden wrapper in the back ground
                  $(currentWrapper).css("background-image",'url'+currentImg);                   // sets up the next image that is now shown in the actually hidden background wrapper
                  $(currentWrapper).show();          //shows the background wrapper, which is not visible yet, and it will be shown the next time the setInterval event will be triggered
                  l++;                         //set the next image index that will be set the next time the setInterval event will be triggered 
             });


         };                   //end of myFunction
  }                          //end of main

i hope that my answer is clear,if you need more explanation comment it.

sorry for my english :)

0

Just have to change

background-image: url(http://upload.wikimedia.org/wikipedia/commons/8/84/Konqi_svg.svg);

to:

background-image: 
linear-gradient(to bottom, rgba(245, 246, 252, 0.52), rgba(117, 19, 93, 0.73)),url(http://upload.wikimedia.org/wikipedia/commons/8/84/Konqi_svg.svg);