Jquery: How do I fade in background image on mousedown?

I have a button that is setup to switch a body background image on mousedown. I want to be able to fade out and then fade in the next loaded image.

My code:


$('#shadows_btn').mousedown(function(){
	$("body").attr('style',"background: #d9d9d9 url('img/shadows_bg.jpg') no-repeat center 4400px;");		
});

Is there any way to do this? I wouldn’t mind it if the current image disappeared by the new image would fade in. Suggestions?

Hi,

AFAIK you can’t fade in a body’s background image using jQuery.
What might work, however is using an image at the beginning of the body:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Fade in example</title>
    <style>img#yourImage {position:absolute;width:100%;height:100%;left:0px;top:0px;z-index:-1; display:none;}&#8203;</style>
    <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
  </head>
  
  <body>
    <img src="a.jpg" id="yourImage" />
    <button id="shadows_btn">Fade in background</button>
    
    <script>
      $(document).ready(function() {
        $('#shadows_btn').mousedown(function(){
          $('#yourImage').fadeIn('slow', function() {
            // Animation complete.
          });			
        });
      });
    </script>
  </body>
</html>

Here’s a demonstration of what I mean, with the image positioned a bit better.

Also, if you just want to set the background image on button press, that’s easy:
$(body).css("background-image", "url(yourPath.jpg)", it’s just the fading part that is hard.

Edit: inspiration found here: http://stackoverflow.com/questions/977090/fading-in-a-background-image