random image selector from a directory with jquery

background, image, jquery, php, random

Solution

You can have a small PHP script returning a random filename from your image directory

<?
    $files = glob('path-to-dir/*.*');
    $file = array_rand($files);
    echo $files[$file];
?>

and call that script with jquery AJAX :

function loadBackground() {
   $.ajax({
      url: 'getimage.php',
      success : function(filename) {
         $('body').css('background-image', 'url('+filename+')');
      }
   });
}

call it each 5 secs

setInterval(loadBackground, 5000);

When styling the background, use the `background`-selector instead of the `background-image` selector :

$('body').css('background', 'url('+filename+') no-repeat center center fixed');

Problem

im using jquery.min. ` function LoadImages() { ` i've tried to use jasper roos winkel jquery plugin to do that but its not necessarily fulfill my needs: http://www.jasperrooswinkel.com/smooth-fullscreen-background-slideshow-in-jquery/ here is my problem: i have a folder with thousands of images on my webserver. i want a dynamic background changer with jquery. which will select one image on every 5 seconds randomly from that folder and put it to the background. how can i do that? waiting for your helps.

Original source