If you already know how to set up your back-end server, here's the setup using Node, Express and Pug
Node: server.js
const express = require('express');
const app = express();
app.set('view engine', 'pug');
app.use(express.static(__dirname + '/public'));
const imagesFolder = './public/images/splash';
const fs = require('fs');
var filesArr = [];
fs.readdir(imagesFolder, (err, files) => {
files.forEach(file => {
filesArr.push(file);
});
});
app.get('/', (req, res) => {
console.log(filesArr);
res.render('splash', {
filesArr : JSON.stringify(filesArr)
});
});
Pug: splash.pug
doctype html
html
body(style='overflow:hidden')
div#theShow(style="height:100%; width:100%; background-repeat:no-repeat; background-position:center;")
script.
const files = JSON.parse('!{filesArr}');
script(src='javascript/splashScreen.js')
JavaScript: splashScreen.js
var slideIndex = 0;
showSlides();
function showSlides(){
var slideshow = document.getElementById('theShow');
slideshow.style.backgroundImage = "url('../images/splash/" + files[slideIndex] + "')";
document.body.removeChild(slideshow);
document.body.appendChild(slideshow);
if (slideIndex < files.length) {
slideIndex++;
} else {
slideIndex = 0;
}
setTimeout(showSlides, 6000);
}
With Node the readdir()
funciton is used to read the directory, and the filesArr
variable is given to the Pug file on the get request
of the \
, a.k.a. the root.
Pug can then access the filesArr
variable using !{}
. The variable files
is set to equal filesArr
within its own script.
and then the external script is called and has access to files
It also worked out better for my use to change the backgroundImage
of a div
rather than the src
of an img
. But the javascript inside splashScreen.js could be easily rewritten to slideshow.src = "url('../images/splash/" + files[slideIndex] + "')";
where slideshow is an img
element instead of a div
.
If, like me you're trying to do this before understanding how to set up a back-end server for your website
There are multiple great resources on the internet about using Node, but sometimes they can be hard to find. It's even harder to find resources about how to get started for an absolute beginner.
This YouTube video is very informative without too much fluff and shows how to get started from nothing. (The hyperlink timestamp starts at 9:20 which is when the actual programming begins, but the first part of the video is informative as well)
After that video, the same YouTuber has a playlist where he makes a wesbite using Node, Express and Pug which you can watch to understand how to set up your back-end server and then you can utilize the code at the top portion of this answer!