Yaky
Yaky

Reputation: 31

Fading effect in background

How can I make my inline styled div to change it background image url after 5 second?

Example:

<div class="foobar" style=" background:(url'red.png')"> </div>

After 5 seconds, it need to be:

<div class="foobar" style=" background:(url'blue.png')"> </div>

and After 5 seconds, it need be:

<div class="foobar" style=" background:(url'yellow.png')"> </div>

So, It can cycle 3 images in this foobar, Red, Blue and Yellow background images.

Here is what I tried so far: Working fiddle

Upvotes: 1

Views: 77

Answers (3)

Piyush k
Piyush k

Reputation: 297

The best way is to use jquery Cycle plugin. You can download it from

http://jquery.malsup.com/cycle/

It's open source and easy to impliment and in addition you can add various effect like fadein, zoom and suffle etc.

Upvotes: 0

Zakaria Acharki
Zakaria Acharki

Reputation: 67505

You have to use setInterval() instead :

setInterval(nextBackground, 5000);

If you want smooth fade in use the fadeIn() function :

imagrep.hide().fadeIn();

NOTE : fadeIn() works only on hidden elements that why we have to hide the element first.

Hope this helps.

$(function() {
  var imagrep = $('.foobar');
  var backgrounds = ['url(http://images.huffingtonpost.com/2016-03-02-1456944747-2376497-naturehike.jpg)', 'url(http://www.mindful.org/wp-content/uploads/2016/03/nature.jpg','url(http://www.planwallpaper.com/static/images/3d-nature-wallpaper1.jpg)'];
  var current = 0;

  function nextBackground() {
    imagrep.css('background',backgrounds[current]);
    imagrep.hide().fadeIn();
    
    if(current==backgrounds.length-1)
      current=0;
    else
      current++;
  }
  
  setInterval(nextBackground,2000);
});
.foobar {
  height: 400px;
  width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="foobar" style="background:url(http://www.planwallpaper.com/static/images/3d-nature-wallpaper1.jpg);">
</div>

Upvotes: 1

Rust in Peace
Rust in Peace

Reputation: 176

You can't animate the background-image (or background with an image) property, but you can get a similar effect like this :

imagrep.animate({opacity: 0}, 'slow', function() {
    imagrep.css({'background-image': backgrounds[current = ++current % backgrounds.length]}).animate({opacity: 1});
});

This animate the opacity to 0, then change the image, and finally animate the opacity to 1.

Here is a jsfiddle: http://jsfiddle.net/m61u51xt/3/

Upvotes: 0

Related Questions