[jquery] Can I fade in a background image (CSS: background-image) with jQuery?

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?

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

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!

This question is related to jquery html css

The answer is


jquery:

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

css

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

html

<div></div>

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 :)


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.


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


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>

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.


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.


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.


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();

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to css

need to add a class to an element Using Lato fonts in my css (@font-face) Please help me convert this script to a simple image slider Why there is this "clear" class before footer? How to set width of mat-table column in angular? Center content vertically on Vuetify bootstrap 4 file input doesn't show the file name Bootstrap 4: responsive sidebar menu to top navbar Stylesheet not loaded because of MIME-type Force flex item to span full row width