Naqib Hakimi
Naqib Hakimi

Reputation: 912

Change Picture in CSS Style Dynamically

I have style id like this

#Myimage {
    width: 797px;
    height: 317px;
    background:url(images/templatemo_header_pizza.jpg) no-repeat;

And I want to change the picture every 5 sec.
I am new to JavaScript and jQuery but the main idea something like this

function ()
{
  ImageArray = LoadImage("Baseimage/*.jpg")

  while(true)
  {
     For(i in ImageArray)
      {
        Myimage.background:url = i;
        waitfor(5);
      }
  }
}

Upvotes: 0

Views: 99

Answers (3)

Downgoat
Downgoat

Reputation: 14371

You can use Image to check if the image exists:

$(function () {
    var base = "myImage_*.jpg", img, c = 0, ar = [], o = 0;
    function recurse () {
        img = new Image();
        img.src = base.replace('*', ++c);
        img.onload = function () {
            ar.push(img.src);
            recurse();
        }
        img.onerror = function () {
            c = -1;
            function r() {
                $("yourElement").css("background-image", "url("+ar[c++ >= ar.length ? (c=0) : c]+")");
                setTimeout(r, 2000); // 2000 is two seconds
            }
        }
    }
});

Upvotes: 0

Muhammad HamZa Khan
Muhammad HamZa Khan

Reputation: 77

Attach a Jquery lib. and past that JQuery script in you head section:

  $(window).load(function() {          
  var i =0;
  var images = ['image2.png','image3.png','image1.png'];
  var image = $('#Myimage');
                //Initial Background image setup
  image.css('background-image', 'url(image1.png)');
                //Change image at regular intervals
  setInterval(function(){  
   image.fadeOut(1000, function () {
   image.css('background-image', 'url(' + images [i++] +')');
   image.fadeIn(1000);
   });
   if(i == images.length)
    i = 0;
  }, 5000);           
 });

Upvotes: 0

Branko Sego
Branko Sego

Reputation: 790

var imgArray = ["image1.jpg","image2.jpg"];
var counter = 0;
function changeImages() {
counter++;
$("#MyImage").css("background-image",'url(' +imgArray[counter]  + ')')
if(counter == 1) {
    counter = -1;
}

}
setInterval(changeImages,5000)

Upvotes: 2

Related Questions