I have a problem that seems small, but it is no longer making me sleep at night, I am probably thinking about it too much and I have lost sight of the correct path!
I\'m
This JS is working..
<div class="container-fluid nopadding" style="width:100vw; min-height: 400px;">
<script language="javascript">
var delay=1500 //set delay in miliseconds
var curindex=0
var randomimages=new Array()
randomimages[0]="img/car1.jpg"
randomimages[1]="img/car5.jpg"
randomimages[2]="img/car2.jpg"
randomimages[3]="img/car4.jpg"
randomimages[4]="img/car3.jpg"
randomimages[5]="img/car6.jpg"
var preload=new Array()
for (n=0;n<randomimages.length;n++)
{
preload[n]=new Image()
preload[n].src=randomimages[n]
}
document.write('<img width="100%" height="100%" class="img-size" <img name="defaultimage" src="'+randomimages[Math.floor(Math.random()*(randomimages.length))]+'">')
function rotateimage()
{
if (curindex==(tempindex=Math.floor(Math.random()*(randomimages.length)))){
curindex=curindex==0? 1 : curindex-1
}
else
curindex=tempindex
document.images.defaultimage.src=randomimages[curindex]
}
setInterval("rotateimage()",delay)
</script>
<!-- Random image slideshow - Thanks to Tyler Clarke (tyler@ihatecoffee.com)
For this script and more, visit http://www.javascriptkit.com -->
Unfortunately, reading data from a directory isn't supported in JavaScript. You might need a server side language like PHP or Node JS to read the directory and add them in HTML.
For example, if it's PHP, you can do something like List all files in one directory PHP. You can use that array to build your array:
<?php
foreach($files as $file) {
echo '<div class="carousel-item transparent" style="background-image: url(img/' . $file . ')"></div>';
}
Or if you're using Node JS, it's still simpler:
const directoryPath = path.join(__dirname, 'Documents');
//passsing directoryPath and callback function
fs.readdir(directoryPath, function (err, files) {
//handling error
if (err) {
return console.log('Unable to scan directory: ' + err);
}
//listing all files using forEach
files.forEach(function (file) {
// Do whatever you want to do with the file
console.log('<div class="carousel-item transparent" style="background-image: url(img/' + file + ')"></div>');
});
});
Ultimately you need a server side language for this.