1

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.

Rajesh
  • 24,354
  • 5
  • 48
  • 79
Yakry
  • 11
  • 1
  • 2
  • will it repeat the images like a loop or show just once?? – Gaurav Aggarwal Jul 05 '16 at 09:49
  • Some hint: You can use `setInterval` to achieve this. Call a function on load of the body tag. Eg:- ` ` – Abhi Jul 05 '16 at 09:49
  • @Andrew I am working on fiddle but not even with class working with simple example. – Yakry Jul 05 '16 at 09:51
  • @GauravAggarwal Yes it will loop – Yakry Jul 05 '16 at 09:51
  • See this links, maybe help you: [css3-fade-effect](http://stackoverflow.com/questions/3079330/css3-fade-effect) and [fade-in-a-background-image](http://stackoverflow.com/questions/7319552/can-i-fade-in-a-background-image-css-background-image-with-jquery) – MHS Jul 05 '16 at 09:51

2 Answers2

2

I wonder if this is what you are looking for?

I have 3 different fades for the background colour. Using CSS keyframes

HTML

<div class="box"> </div>

CSS

@keyframes colorbox {
  0% {
    background:red;
  }
  40% {
    background: green;
  }
  80% {
    background: blue;
  }
  100% {
    background: red;
  }
}

.box {
   width:200px;
   height:200px;
   animation: colorbox 5s infinite ease-in-out;
}

See it working

JSFIDDLE

If you need some more information about CSS Keyframe animations have a look a look at this link: https://css-tricks.com/snippets/css/keyframe-animation-syntax/

Andrew
  • 1,850
  • 14
  • 18
0

You need to do following things:

  1. Create a timeout that will run after specific delay and do some task
  2. You will have to use fadeOut and fadeIn for bounce effect.
  3. You will have to reset class and add corresponding class. This needs to be done after fadeOut and before fadeIn.

Sample

JSFiddle

var count = 1;
var class_list = ["red", "blue", "green"];
function animateDiv(){
 $("#content").fadeOut(400,updateClass);
}

function updateClass(){
 $("#content").removeClass("red blue green").addClass(class_list[count++ % class_list.length]).fadeIn(400);
}

function initInterval(){
 setInterval(animateDiv, 2000);
}

$(document).ready(function(){
 initInterval();
})
.red{
  background: red;
}
.blue{
  background:blue;
}
.green{
  background: green;
}
div{
  width: 100px;
  height:100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="content" class="red"></div>

Note: You will have to pass fadeIn code as a callback, so that it is executed after fadeOut is completed.

Reference

Rajesh
  • 24,354
  • 5
  • 48
  • 79