mctuna
mctuna

Reputation: 871

Jquery replacing body background-image with fadeout and fadein effect

I just want to change background-image of body with a fadeOut and replace the second image with fadeIn.
But I get the following error:

Uncaught TypeError: Object url(file:///C:/Users/.../p1bg_cutted.png) has no method 'fadeOut'
 $('body').css("background-image").fadeOut('slow',function(){
    $("body").css("background-image",
    "url(Images/son_componentler/p2bg_cutted.png)").fadeIn('slow')

 });

I can change the image without fadein/fadeout but I guess in that case I am making a sytax mistake.

Upvotes: 3

Views: 11190

Answers (2)

Aust
Aust

Reputation: 11602

Instead of fading out the body and then fading it back in. You can get the exact same effect by fading in a masking div that covers the whole screen, change the background-image of the body, and then fading out the masking div. Something like this:

HTML - Add this line anywhere in your HTML

<div id="mask" style="position: absolute; top: 0; left: 0; background: black; display: none;"​​​​​​​​​​​​​​​​​​​​​​></div>​

JavaScript

$('#mask').css({height: $(window).height(), width: $(window).width()})
          .fadeIn('slow', function(){
              $('body').css('background-image', 'url(Images/son_componentler/p2bg_cutted.png)');
              $('#mask').fadeOut('slow');
          });​​​​​

See a working example here


UPDATE

In one of my projects I wanted to fade everything to black and then back in with a different image which is what my original code did. If you want to keep the content visible, you don't have to change much. Just have a div in the background with your image. Then apply the masking technique over only your background image.

HTML

<div id="img" style="position: absolute; z-index: -99; top: 0; left: 0;"></div>
<div id="mask" style="position: absolute; z-index: -98; top: 0; left: 0; background: white; display: none;"></div>

JavaScript

$('#mask').css({height: $(window).height(), width: $(window).width()})
          .fadeIn('slow', function(){
              $('#img').css('background-image', 'url(http://www.jsfiddle.net/img/logo.png)');
              $('#mask').fadeOut('slow');
          });

See a working example here

Upvotes: 0

Salman Arshad
Salman Arshad

Reputation: 272156

You code fails because $('body').css("background-image") returns a string -- the value of the CSS background image property; not a jQuery object.

Secondly, your code will fade in/fade out the entire body. Background image itself can not be faded.

I suggest that you use an img positioned behind content and fade it.

Upvotes: 4

Related Questions