Question

I would like to change an image in my site with fading effect. The thing is that I am using two different classes for the same div, so actually I want to fade out one class and in the meanwhile start fading in the second class, before the first one has been completely removed.

HTML:

 <div id="background_image" class="day"></div>

CSS:

 .day{
      background: url(day.png);
  }

 .night {
     background: url(night.png);
 }

JQuery:

setTimeout(function(){
    if($("#background_image").hasClass("day")){
        $("#background_image").fadeOut(function() {
            $(this).removeClass("day");  
        });

        $("#Landscape").fadeIn(function() {
            $(this).addClass("night");  
        });
    }else{
           $("#background_image").fadeOut(function() {
            $(this).removeClass("night");  
        });

        $("#Landscape").fadeIn(function() {
            $(this).addClass("day");  
        });
    }
}, 5000);

But this code makes the image "day.png" first to disappear completely and then the "night.png" comes which is not what I want. Is there a way to fade out the class "day" and start fade it "night" without having a blank space between the fading? Thanks in advance

Was it helpful?

Solution

It seems that what you're trying to do is cross-fading. This is normally done using 2 divs. If this is for the entire background, then I suggest http://srobbin.com/jquery-plugins/backstretch/. You can take a look at their implementation to narrow it down to just a div if you don't need it to cover the entire background.

This is how I solved it for a similar case.

var images = [
   "/content/images/crane1.jpg",
   "/content/images/crane2.jpg",
   "/content/images/crane-interior.jpg"
];
// The index variable will keep track of which image is currently showing
var index = 0;

// Call backstretch for the first time,
// In this case, I'm settings speed of 500ms for a fadeIn effect between images.
$.backstretch(images[index], { speed: 500 });

// Set an interval that increments the index and sets the new image
// Note: The fadeIn speed set above will be inherited
setInterval(function () {
    index = (index >= images.length - 1) ? 0 : index + 1;
    $.backstretch(images[index]);
}, 5000);

EDIT: For non-full background, take a look at this post Crossfade Background images using jQuery

Also take a look at this, might be closer to your scenario Cross fade background-image with jQuery

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top