Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

random image selector from a directory with jquery

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.

like image 574
haybeye Avatar asked Feb 20 '26 02:02

haybeye


1 Answers

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');
like image 170
davidkonrad Avatar answered Feb 21 '26 15:02

davidkonrad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!