32

I finally have this working now but would like to know how I can use JQuery's animate function to make the background image changes fade in nicely when you hover over the list items on the homepage:-

http://www.thebalancedbody.ca/

The Code to make this happen so far is:-

$("ul#frontpage li#277 a").hover(
    function() {
        $('#homepage_container').css('background-image', 'url(http://www.thebalancedbody.ca/wp-content/themes/balancedbody_V1/images/nutrition_background.jpg)');
    },
    function() {
        $('#homepage_container').css('background-image', 'url(http://www.thebalancedbody.ca/wp-content/themes/balancedbody_V1/images/default_background.jpg)');
    }
);

$("ul#frontpage li#297 a").hover(
    function() {
        $('#homepage_container').css('background-image', 'url(http://www.thebalancedbody.ca/wp-content/themes/balancedbody_V1/images/vibration_training.jpg)');
    },
    function() {
        $('#homepage_container').css('background-image', 'url(http://www.thebalancedbody.ca/wp-content/themes/balancedbody_V1/images/default_background.jpg)');
    }
);

etc etc

How would I add the ANIMATE function to this please - thanks!!!

Thanks

Jonathan

Narendra Jadhav
  • 10,052
  • 15
  • 33
  • 44
Jonathan Lyon
  • 3,862
  • 7
  • 39
  • 52
  • Here's the link to the solution [Link to Solution - set css with fade in and delay](http://stackoverflow.com/questions/5002351/how-to-fade-changing-background-image) – Zee Mar 08 '17 at 20:33

9 Answers9

32

I don't think this can be done using jQuery's animate function because the background image does not have the necessary CSS properties to do such fading. jQuery can only utilize what the browser makes possible. (jQuery experts, correct me if I'm wrong of course.)

I guess you would have to work around this by not using genuine background-images, but div elements containing the image, positioned using position: absolute (or fixed) and z-index for stacking. You would then animate those divs.

Pekka
  • 442,112
  • 142
  • 972
  • 1,088
  • so if the background image was one big image (like a sprite) I could then animate the moving / repositioning of this sprite using Anmiate? – Jonathan Lyon Jun 06 '10 at 11:15
  • 6
    @Jonathan - Yes, by animating `background-positon`, like this: http://snook.ca/technical/jquery-bg/ – Nick Craver Jun 06 '10 at 11:16
  • @Nick good link! @Jonathan what I meant went more in the direction of having two `div`s underneath each other, and fading one of them out or in. (If you are looking to *fade* the images.) the animation method is certainly easier. – Pekka Jun 06 '10 at 11:34
  • +1 for that link. I started using that plugin some time ago and it just rocks that i can now animate background images! :) See one of my latest bg animations here: http://mashinaizec.com/ where i am animating this image: http://mashinaizec.com/css/images/nav_background.png – Gavrisimo Jun 06 '10 at 11:35
  • hi guys I have created one big image that can be moved by using background-position:0px -600px for the second list item, then background-position:0px -1200px; for the third list item etc but I can't trigger this in the javascript using the hover event of each list item to animate and move the background image of homepage_container - any ideas? this is the bg image http://www.thebalancedbody.ca/wp-content/themes/balancedbody_V1/images/homepageimages.jpg – Jonathan Lyon Jun 06 '10 at 11:51
  • I'm just not sure how to write it in javascript – Jonathan Lyon Jun 06 '10 at 11:53
  • @Jonathan maybe the source code of the example @Nick linked to helps? It contains full `animate` statements, do those come close to what you're looking for? – Pekka Jun 06 '10 at 11:56
  • I think I have done it correctly but can't get it to work $("ul#frontpage li#277 a").hover( function () { $('#homepage_container').stop().animate({backgroundPosition:"(0 -1200)"}, {duration:500}); },function () { $('#homepage_container').stop().animate({backgroundPosition:"(0 0)"}, {duration:500});; } ); – Jonathan Lyon Jun 06 '10 at 12:03
  • @Jon you are missing the `px` unit values in the backgroundPositions. – Pekka Jun 06 '10 at 12:11
  • Thanks Pekka - It could have been that or not linking to the bgpos.js file properly - anyhow it's working now http://www.thebalancedbody.ca/ - however, I would rather have it FADE into each image rather than slide. Any ideas? – Jonathan Lyon Jun 06 '10 at 12:49
  • @Jon as I said, you won't be able to fade that way. See whether @XGreen's approach works for you. – Pekka Jun 06 '10 at 12:59
  • I just figured it out, check out my answer. Heh, I didn't realize it but it's exactly what you say in your post. – Milimetric Jun 15 '12 at 14:21
18

building on XGreen's approach above, with a few tweaks you can have an animated looping background. See here for example:

http://jsfiddle.net/srd76/36/

$(document).ready(function(){

var images = Array("http://placekitten.com/500/200",
               "http://placekitten.com/499/200",
               "http://placekitten.com/501/200",
               "http://placekitten.com/500/199");
var currimg = 0;


function loadimg(){

   $('#background').animate({ opacity: 1 }, 500,function(){

        //finished animating, minifade out and fade new back in           
        $('#background').animate({ opacity: 0.7 }, 100,function(){

            currimg++;

            if(currimg > images.length-1){

                currimg=0;

            }

            var newimage = images[currimg];

            //swap out bg src                
            $('#background').css("background-image", "url("+newimage+")"); 

            //animate fully back in
            $('#background').animate({ opacity: 1 }, 400,function(){

                //set timer for next
                setTimeout(loadimg,5000);

            });

        });

    });

  }
  setTimeout(loadimg,5000);

});
Delmontee
  • 1,898
  • 2
  • 26
  • 44
15
<style type="text/css">
    #homepage_outter { position:relative; width:100%; height:100%;}
    #homepage_inner { position:absolute; top:0; left:0; z-index:10; width:100%; height:100%;}
    #homepage_underlay { position:absolute; top:0; left:0; z-index:9; width:800px; height:500px; display:none;}
</style>

<script type="text/javascript">
    $(function () {

        $('a').hover(function () {

            $('#homepage_underlay').fadeOut('slow', function () {

                $('#homepage_underlay').css({ 'background-image': 'url("http://www.thebalancedbody.ca/wp-content/themes/balancedbody_V1/images/nutrition_background.jpg")' });

                $('#homepage_underlay').fadeIn('slow');
            });

        }, function () {

            $('#homepage_underlay').fadeOut('slow', function () {

                $('#homepage_underlay').css({ 'background-image': 'url("http://www.thebalancedbody.ca/wp-content/themes/balancedbody_V1/images/default_background.jpg")' });

                $('#homepage_underlay').fadeIn('slow');
            });


        });

    });

</script>


<body>
<div id="homepage_outter">
    <div id="homepage_inner">
        <a href="#" id="run">run</a>
    </div>
    <div id="homepage_underlay"></div>
</div>

makeitmorehuman
  • 11,287
  • 3
  • 52
  • 76
11

I had the same problem, after loads of research and Googling, I found the following solution worked best for me! plenty of trial and error went into this one.

--- SOLVED / SOLUTION ---

JS

$(document).ready(function() {
            $("header").delay(5000).queue(function(){
                $(this).css({"background-image":"url(<?php bloginfo('template_url') ?>/img/header-boy-hover.jpg)"});
            });
        });

CSS

header {
    -webkit-transition:all 1s ease-in;
    -moz-transition:all 1s ease-in;
    -o-transition:all 1s ease-in;
    -ms-transition:all 1s ease-in;
    transition:all 1s ease-in;
}
Brad Fletcher
  • 3,547
  • 3
  • 27
  • 42
3

It can be done by jquery and css. i did it in a way that can be used in dynamic situations , you just have to change background-image in jquery and it will do every thing , also you can change the time in css.

The fiddle : https://jsfiddle.net/Naderial/zohfvqz7/

Html:

<div class="test">

CSS :

.test {
  /* as default, we set a background-image , but it is not nessesary */
  background-image: url(http://lorempixel.com/400/200);
  width: 200px;
  height: 200px;
  /* we set transition to 'all' properies - but you can use it just for background image either - by default the time is set to 1 second, you can change it yourself*/
  transition: linear all 1s;
  /* if you don't use delay , background will disapear and transition will start from a white background - you have to set the transition-delay the same as transition time OR more , so there won't be any problems */
  -webkit-transition-delay: 1s;/* Safari */
  transition-delay: 1s;
}

JS:

$('.test').click(function() {
  //you can use all properties : background-color  - background-image ...
  $(this).css({
    'background-image': 'url(http://lorempixel.com/400/200)'
  });
});
Ali Naderi
  • 74
  • 6
2

Have a look at this jQuery plugin from OvalPixels.

It may do the trick.

1

The simplest solution would be to wrap the element with a div. That wrapping div would have the hidden background image that would appear as the inner element fades.

Here's some example javascript:

$('#wrapper').hover(function(event){
    $('#inner').fadeOut(300);
}, function(event){
    $('#inner').fadeIn(300);
});

and here's the html to go along with it:

<div id="wrapper"><div id="inner">Your inner text</div></div>
Jason
  • 1,081
  • 10
  • 24
0

Ok, I figured it out, this is pretty simple with a little html trick:

http://jsfiddle.net/kRjrn/8/

HTML

<body>
    <div id="background">.
    </div>
    <p>hello world</p>
    <p>hello world</p>
    <p>hello world</p>
    <p>hello world</p>    
</body>​

javascript

$(document).ready(function(){
    $('#background').animate({ opacity: 1 }, 3000);
});​

CSS

#background {
    background-image: url("http://media.noupe.com//uploads/2009/10/wallpaper-pattern.jpg");
    opacity: 0;
    margin: 0;
    padding: 0;
    z-index: -1;
    position: absolute;
    width: 100%;
    height: 100%;
}​
Milimetric
  • 13,411
  • 4
  • 44
  • 56
0
$('.clickable').hover(function(){
      $('.selector').stop(true,true).fadeTo( 400 , 0.0, function() {
        $('.selector').css('background-image',"url('assets/img/pic2.jpg')");
        });
    $('.selector').fadeTo( 400 , 1);
},
function(){
      $('.selector').stop(false,true).fadeTo( 400 , 0.0, function() {
        $('.selector').css('background-image',"url('assets/img/pic.jpg')");
        });
    $('.selector').fadeTo( 400 , 1);
}

);
Artem
  • 81
  • 6