Using JavaScript to dynamically alter the background image of an HTML document from a selection of filenames

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!

Answer №1

When working with the browser, using fs is not allowed in this manner. Instead, you should store paths to images. These paths can be stored in a database or an array within your javascript file. Here's an example of storing filenames in an array:

function main()
{
    var images = ['image1.jpeg', 'image2.jpg', 'bg.png'] //storing only names
    var index = Math.floor(Math.random() * images.length)
    var filePath = "Background/" + images[index]; //creating full path
    document.body.style.background = 'url("'+filePath+'")'
    // if background-size is not changing, it's better to store it in .css file
}

$(document).ready(main);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What could be causing my div elements to not appear on the page?

Hey there, this is my debut post here so bear with me on the formatting. I'm currently working on a project and encountering some hurdles with my divs. Even though I've left space for them, I just can't seem to get my divs (or cards) to disp ...

Sections overlap, extending the content beyond their designated boundaries

I am facing an issue where the header in the first section remains fixed as an attachment, but when I resize the browser window, the background only covers a small portion of the section. The rest of the content either goes under another section or complet ...

Issue with pagination and filtering in Smart-table.js

Presently, my focus is on developing functionality for Smart-table.js, which requires the following features: Retrieve JSON data from a web service Create a table with pagination and filtering capabilities Implement filters for individual columns or globa ...

Enhance React form rendering efficiency

Is there a way to improve the rendering of a 'form' component when a key is pressed? Any suggestions on how to optimize this process? const Example = () => { const [inputForm, setInputForm] = useState(''); const inputHandler = e ...

ways to run php script based on screen resolution or size

I have 2 php files that I need to execute based on screen size. include_once('large.php'); include_once('small.php'); The condition is to run large.php when the screen size is greater than 992px, and small.php when the screen size is ...

The value of the variable is failing to be included in the Ajax request being sent to the server via jQuery

I'm encountering an issue with my contact form where I can't seem to retrieve the $_POST values via ajax for saving to a text file. It seems like there might be a problem with my javascript code. Check out the jQuery code snippet below: functio ...

Creating a searchable and filterable singleSelect column in the MUI DataGrid: A step-by-step guide

After three days of working on this, I feel like I'm going in circles. My current task involves fetching data from two API sources (json files) using the useEffect hook and storing them in an array. This array contains a large number of products and a ...

Refreshing a Nested Component Within a Parent Component in React

Currently, I am in the final stage of a small project where a Higher Order Component (HOC) is being utilized to display a basic Tinder-like application. The internal component is a class-based component containing its own fetch() call that presents user d ...

Ensuring one div remains in a fixed position relative to another div

I'm struggling to keep my two white divs aligned in relation to the black div in the center. They need to maintain the same distance from the black div even when the page is resized. #halvfjerds { width: 100%; height: 1050px; background-color ...

Leveraging server-side data with jQuery

When my client side JQuery receives an array of JSON called crude, I intend to access and use it in the following way: script. jQuery(function ($) { var x = 0; alert(!{JSON.stringify(crude[x])}); ...

The CSS code is effective on one page but fails to render on the other

I am in the process of creating a website for my jewelry business and it's my first time doing so. I'm facing an issue where the CSS styles are being applied to one page but not to the other, even though both HTML files have the same code linking ...

Problem with Vue.js dropdown functionality in Internet Explorer

After developing a form using Vue.js to allow users to save and return to their answers, I encountered an issue in Internet Explorer. When the page loads, the dropdown menu tied to a computed property does not display the previously selected answer as expe ...

Use the powerful $.post() method to transfer an image to another page seamlessly

I have two pages, the first page contains a form where users can enter information such as name and mobile number. Additionally, they can upload an image. I would like to use jQuery to access the uploaded image and send it to another page using the $.post( ...

ReactJS - When a child component's onClick event triggers a parent method, the scope of the parent method may not behave as anticipated

In my current setup, I have a parent component and a child component. The parent component contains a method within its class that needs to be triggered when the child component is clicked. This particular method is responsible for updating the store. Howe ...

Opinions on crafting a new gadget?

I will only provide each website interested in my widget with the code to copy and paste once. It is crucial that the code is future-proof. After much consideration, this is the widget code I have developed: <script type="text/javascript" src="http:/ ...

Sharing parameters between functions in JavaScript

I have a working code but I want to modify the function getLocation to accept 2 arguments that will be passed to getDistanceFromLatLonInKm within the ajmo function. Currently, getDistanceFromLatLonInKm has hardcoded arguments and I would like to use variab ...

How can I determine which component the input is coming from when I have several components of the same type?

After selecting two dates and clicking submit in the daterange picker, a callback function is triggered. I have two separate daterange pickers for SIM dates and Phone dates. How can I differentiate in the callback function when the user submits dates from ...

Click on the links to view various captions for a single image, one at a time

My goal is to create an interactive image similar to what can be found at . (Click Play and navigate to page 5 to see the interactive physical exam). While this example seems to use Flash, I am interested in achieving a similar effect using javascript/jQue ...

Adjust the placement of image when changing the size of the window

Is there a way to prevent an image with a fixed position from covering up page content when the browser window is resized? <div > <img id="img1" class="wrapperImage"></img> </div> <style type="text/css"> .wrapperImag ...

Automatically changing the color of the navigation bar text

I am experiencing an issue with the navigation bar on my webpage. Currently, it is styled with white text against a dark background color using the following CSS code snippet: a{ color: white; text-decoration:none; font-weight:bold; font-s ...