Just starting out with JavaScript and working on a simple project. My goal is to have the background image of an HTML document change to a random picture from a directory named 'Background' every time the page is opened.
function main()
{
// Creates a list of filenames from the 'Background/' dir and gets a
// random index in the list
var fs = require('fs');
var fileList = fs.readdirSync('/Background/');
var len = fileList.length;
var index = Math.floor(Math.random() * len);
var filePath = "Background/" + fileList[index];
document.body.style.backgroundImage = "url(filePath)";
document.body.style.backgroundSize = "cover"
}
$(document).ready(main);
However, I'm running into issues as the code doesn't seem to work as intended. I suspect my misunderstanding lies within how the URL class functions. When I manually specify a specific image path like this:
document.body.style.backgroundImage = "url('Background/green.jpg')";
The background image changes successfully, but it's not working with randomly retrieving filenames. It seems to be a language-related error that I can't quite wrap my head around. Any help would be greatly appreciated. Thanks!