Search code examples
jquerycssbackground-image

CSS - Rotating a Background Image


I have a CSS style that uses a background image (code: background-image: url("folderimage.jpg");). Is there a way using jQuery/CSS to rotate between multiple CSS Background Images? (Please provide an example).


Solution

  • Something of this sort would work. I haven't tested the code, but the idea is to have an array of five images and change them after a timeout. I can explain the code if you need.

    var theImages = new Array(); 
    
    theImages[0] = '1.gif'
    theImages[1] = '2.gif'
    theImages[2] = '3.gif'
    theImages[3] = '4.gif'
    theImages[4] = '5.gif'
    
    function changeBGImage(){
      var whichImage = Math.round(Math.random()*(p-1));
      jQuery('#elementHavingProperty').css('background-image','url('+theImages[whichImage+'])');
    } 
    
    movement = setTimeout("changeBGImage()",1000000);