0

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);
      }
  }
}
1
  • a animation would great between changes Commented Jul 5, 2015 at 6:46

3 Answers 3

2
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)
Sign up to request clarification or add additional context in comments.

2 Comments

thanks, but this line does not work for me $("#MyImage").css("background-image",'url(' +imgArray[counter] + ')') is there any support problems i am using int.explorer
@user3717658 wrap the code in a $(function, take a look at the other answers to see how to use this. The other thing could be jQuery isn't loaded
0

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);           
 });

Comments

0

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
            }
        }
    }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.