0

I have a div element with background image, I'm trying to fade in and out background images with Jquery. By now the function works well but it fades out the whole div and not only the background as I wish.

function rentPics()
{
    $('#d2').css('background-image','url(' + mazdaArr[1] + ')');
    interID=setInterval (changeImage,3000);
}

function changeImage()
    {
        $('#d2').animate({opacity: 0}, 1500, function(){
        $('#d2').css('background-image', 'url(' + mazdaArr[x] + ')');
        }).animate({opacity: 1}, 1500);
        x++;
        if (x==mazdaArr.length)
        {
            x=1;
        }
    }
Juvi
  • 1,078
  • 1
  • 19
  • 38

4 Answers4

2

If you're looking for a simple and lightweight cross-fading, use the CSS transition. This won't affect the text inside the element, the border and the box-shadow.

transition: background-image 1s ease-in-out;
-webkit-transition: background-image 1s ease-in-out;
-moz-transition: background-image 1s ease-in-out;
-ms-transition: background-image 1s ease-in-out;
-o-transition: background-image 1s ease-in-out;

Check out this fiddle.

It's supported by Chrome, Safari and Opera but I'm not quite sure with Firefox and IE

If you have a larger list of images to loop. You may also want to consider caching the images URL first because I noticed some flickering/blinking on first use. Check solutions here - Preloading CSS Background Images

Community
  • 1
  • 1
Mark S
  • 3,789
  • 3
  • 19
  • 33
0

The fade in applies opacity to the entire div with the background image incluide, you can do this creating a layer behind the div that you want apply the fade in and fade out.

0

Instead of using jQuery to animate opacity, you could have it add or remove a class. Then add transitions to your CSS, which should produce your desired result. Something like below might work. You can see the documentation of CSS transitions here. The only drawback is IE, per usual.

.element {
  -webkit-transition: ease 0.2 all;
  -moz-transition: ease 0.2 all;
  -o-transition: ease 0.2 all;
  -ms-transition: ease 0.2 all;
  transition: ease 0.2 all;
}
vernak2539
  • 574
  • 3
  • 14
0

Use a relative container with an absolute positioned overlay. Your HTML should look like this:

<div id="d2" class="image-wrapper">
  <img src="/img/1.jpg" />
  <div class="overlay"> your text goes here </div>
</div>

... and your CSS:

.image-wrapper {
    position: relative;
}
.image-wrapper .overlay {
    position: absolute;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    overflow: auto;
}
.image-wrapper img {
    display: block;
}

Now you can change the opacity of your image without changing the content within the ovelay.

meavo
  • 1,042
  • 1
  • 7
  • 16
  • I'm not sure you got me right, I dnt have any text I just want that the fade affect wont take the border, box shadows etc.. with it. I want only the image to change... – Juvi Nov 12 '13 at 22:35