user1072337
user1072337

Reputation: 12935

How to fade background images (from CSS) in and out with jquery

As the question says I am trying to fade background images from one image to another for a few images. I would like the initial image to appear immediately on page load, and then have it fade to the next image, then to the next, and back to the first, ongoing.

I have the background image in CSS:

.banner-image { 
background:transparent url('../images/8662834823_575a23516d_o.jpg') no-repeat center center;
-webkit-background-size:cover;
-moz-background-size:cover;
background-size:cover; 
height:800px; 
min-width: 1200px;
}

HTML:

<div class="banner-image">

//Content here
</div> 

I would like the banner-image div to maintain it's height (so other div's appear below it). Which is why I want to maintain the images as CSS backgrounds.

How would I fade between images in jquery with the above requirements? Thank you for your help.

Upvotes: 4

Views: 9180

Answers (3)

Rohit Suthar
Rohit Suthar

Reputation: 3628

Try this demo - Cross fading images using CSS3

http://css3.bradshawenterprises.com/cfimg/

Upvotes: 0

Yotam Omer
Yotam Omer

Reputation: 15356

This is the simplest way to do this without a plugin: jsFiddle

Basically what I did here:

  1. Created a parent #bannerContainer which has position:relative;
  2. Added position:absolute; top:0px; left:0px; to .banner-image.
  3. Inserted a few .banner-image into the parent, giving each a different background image
  4. Applied the following jQuery:

    $(function(){
    
        var t = setInterval(function(){
    
            $('.banner-image').last().fadeOut(2000,function(){ // 2 second fade duration
                $this = $(this);
                $parent = $this.parent();
                $this.remove().css('display','block'); // remove the faded element
                $parent.prepend($this); // put it as the first element
            });
    
        },3000); // every 3 seconds
    });
    

Markup:

<div id="bannerContainer">  
    <div class="banner-image"></div>
    <div class="banner-image" style="background-image:url(http://ns223506.ovh.net/rozne/00032cb2e758642ee9a942b49689f775/wallpaper-11152.jpg)"></div>
    <div class="banner-image" style="background-image:url(http://ns223506.ovh.net/rozne/9d1a802255f5c645945047acb4a2bac6/wallpaper-263.jpg)"></div>
    <div class="banner-image" style="background-image:url(http://ns223506.ovh.net/rozne/bd72cad0602bb9e53b4dc7f3fa4d4db9/wallpaper-4635.jpg)"></div>
</div>

Upvotes: 3

sdespont
sdespont

Reputation: 14025

It is not a plug and play solution, but here is a JQuery code to change the background image with a fadein effect

$(document).ready(function(){
    $('.banner-image').css({opacity: 0, background-image: 'url(../images/new.jpg)'}).fadeIn(2000);
});

Specify also some others CSS properties like background-size to maintain the ratio you want.

Upvotes: 1

Related Questions