0

Psuedo Code:

if currentCondition is snow {
    aFunction()
} else {
    // something else
}

function aFunction {
    look inside the snow folder at /images/condition/snow
    chose random jpeg/jpg from that folder
    use JQuery to set the css background-image property of a div 
}

How would I make the above in JavaScript? I can accomplish everything except choosing the random picture inside the snow folder. Thanks.

EDIT: The files are incrementing (file_1.jpg, file_2.jpg, etc.)

urwoi
  • 61
  • 2
  • 5
  • 1
    You can't do that with just JavaScript, unless the images are all named in a specific way, because JS doesn't have direct access to the server. "Looking inside the folder" must be done with backend scripting, i.e. PHP / node.js / etc –  Jul 04 '17 at 00:20
  • Depends on which webserver you're using. nginx can provide JSON-formatted directory indexes for example, which you could grab with an ajax call: http://nginx.org/en/docs/http/ngx_http_autoindex_module.html#autoindex_format (...but that does imply opening up directory listings to all visitors, which may not be desirable. See also https://stackoverflow.com/questions/20448339/apache-directory-listing-as-json) – Daniel Beck Jul 04 '17 at 00:43
  • @ChrisG I edited the question. he files are incrementing (file_1.jpg, file_2.jpg, etc.). – urwoi Jul 04 '17 at 01:26

2 Answers2

0

This example shows you that, if you have image in 'images/' directory with all the images named as image_0.jpg, image_1.jpg, image_2.jpg incrementing ... change the image file name structure according to your requirement. (Javascript directly cannot search file in server directory, as this might be helpful)

<img src="" align="middle" border="0" name="RandomImg" >

<script language="JavaScript">
// Genarate random value from 0-5, change 6 to any number you want
var rand_no = Math.floor(6*Math.random());

// This defines the source of the preview image  (For example images/image_0.jpg)
document.images['RandomImg'].src="images/image_" + rand_no + ".jpg";

</script>  
Sagun Gautam
  • 470
  • 6
  • 20
0

Here's how to pick a random image, provided the number of images is set:

var totalBGs = 15;
var rnd = Math.floor(Math.random() * totalBGs) + 1; // 1 - 15

Next you need to set that as CSS background (jQuery):

$(document).ready(function () {
  $("#some_element").css({ backgroundImage: "url(path/to/img/file_" + rnd + ".jpg)" });
});