The JavaScript script that is supposed to change backgrounds is malfunctioning

Trying to develop a simple function that alters the background of a specific element when it is clicked by the user


const customFunction = document.querySelectorAll("article .customClass");

const changeBackground = function() {

    const backgrounds = new Array();
    backgrounds[0] = new Image();
    backgrounds[0].src = 'images/image1.jpg';

    backgrounds[1] = new Image();
    backgrounds[1].src = 'images/image2.jpg';

    backgrounds[2] = new Image();
    backgrounds[2].src = 'images/image3.jpg';

    const randomIndex = Math.floor(Math.random() * backgrounds.length);

    const randomBg = backgrounds[randomIndex];
    
    customFunction.style.backgroundColor = randomBg;
    console.log('The user clicked and changed the color to ' + randomBg);

};

customFunction.onclick = changeBackground;

Encountering an issue with the backgrounds function array, struggling to identify the problem despite having checked syntax and references. Any insights?

Answer №1

To modify the background image of an element, you can use the following code snippet:

element.style.backgroundImage = `url(${newBackground.src})`;

For proper display, it may be necessary to adjust some additional styles to ensure the image fits the container correctly:

element.style.backgroundSize = "contain";
element.style.backgroundRepeat = "no-repeat";

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

When the table is clicked, a dynamic accordion table should appear

My current code displays a table inside another table using a PHP for loop. While I can retrieve the data successfully, I'm facing issues with the UI layout and accordion functionality. The inner table is displaying beside the outer table instead of b ...

Guide on creating frozen columns in an Angular 2 table with the ability to scroll through multiple columns

Within my table, there are 3 columns that must always remain on the left side. Additionally, there is a column containing a grid where each element represents an hour of the day, requiring it to be scrollable. I have attempted various proposed solutions, ...

Firefox changes the sequence of form input attributes

Is anyone familiar with this issue and how to prevent it? I am using AJAX to populate a div with a form from a PHP file. The input element is generated in PHP as shown below: echo ('<input type="text" name="court_type_name" id="court_type_name_in ...

Developing a Type-inclusive TypeScript encapsulation for the first level of Array.flat() with generic functionality

I am working on creating a function that constructs an array from the input arguments, allowing for only one type or arrays of that same type. Essentially like (...items)=>items.flat(1), but with type safety and generics. It seems crucial to ensure that ...

How can I apply borders to individual columns within a Bootstrap table without affecting the rows?

My attempted solution involved adding th and tfoot. However, I faced issues with applying borders to only the td elements - border was not being applied at the bottom of the table, and the thickness and color of the borders were inconsistent between column ...

Ways to change a string to an array in Javascript

What is the procedure for transforming the given JSON data into a more concise format? [{"id":6,"name":"r6","preparation_time":"123","servings":4,"background_media_file":"recipe_background_image","font_color":"#000000","created_at":"2020-09-11 09:27:02", ...

Is there a straightforward way to upload a folder in a ReactJS application?

I am searching for a way to upload a folder in ReactJS. I have a folder with .doc and .docx files in it, and I want the user to be able to upload the entire folder when they click the browse button. I need to prevent the user from selecting individual fi ...

What measures can be taken to stop both of these cubes from being dragged simultaneously?

Check out this drag example: https://codepen.io/alexcheninfo/pen/vKkgkE. You'll notice that if you stack cubes and drag the one in front, the one behind it moves as well. Take a look at the complete code below: <script> AFRAME.registerCompon ...

I'm encountering an issue in Django where I am struggling to retrieve the id from the HTML. The specific error message reads: "The field 'id' was expecting a number but received a different value

Once the user selects a translator name, my aim is to retrieve the selected translator's information in Django using their ID and store it in an appointment table within the database. However, I encountered an error when trying to match the ID, which ...

Strategies for optimizing the storage of data from react-quill to the backend system

My current project involves developing a blogging site using react. I am incorporating the use of react-quill for the text editor functionality, but I'm facing a challenge in determining the most efficient way to store the data generated by this edito ...

Is the Data Being Saved: Verifying if the Value Has Been Altered?

Imagine your form containing numerous fields, where typically only 1 or 2 are modified and require saving. What approach do you take? Update the database with all values, regardless of any changes. Utilize form states to post back only the changed values ...

Discovering every element on a webpage while scrolling with the help of Selenium WebDriver and the Python programming language

I've been struggling to scrape all elements from a webpage using Selenium. Despite my efforts, I can't seem to retrieve more than 6 elements out of at least 30 on the URL provided. Can you help me identify what I might be overlooking in my code? ...

Having trouble retrieving a dynamic name with Formcontrol error?

I keep encountering a typeError in this section of code <p *ngIf="formValue.controls['{{obj.name}}'].invalid, but when I manually enter it like this *ngIf="formValue.controls['uname'].invalid it works perfectly fine. What ...

Remove search results in real-time

I'm currently working on implementing a search feature for a web application. While I have made some progress, I am facing an issue with removing items when the user backspaces so that the displayed items match the current search query or if the searc ...

Incorporate the {{ }} syntax to implement the Function

Can a function, such as toLocaleLowerCase(), be used inside {{ }}? If not, is there an alternative method for achieving this? <div *ngFor="let item of elements| keyvalue :originalOrder" class="row mt-3"> <label class=" ...

Combining multiple 'Eithers' and 'Promises' in fp-ts: A guide to piping and chaining operations

Recently, I began working with fp-ts and wanted to create a method with functional-like behavior that would: Parse a bearer token Verify the validity of the user using the parsed token import { Request } from 'express'; import { either } from & ...

Top method for organizing an array based on an object's property and displaying the outcome

I encountered a problem for which I couldn't find an immediate solution. I have an array of objects representing products, with each product having a category property. My goal is to group these products by their categories. After some trial and error ...

Unable to detect cookie presence in header due to reading issue

Kindly review the image provided via the following link. https://i.sstatic.net/innYb.png The front-end code initiates a call to the back-end API to log in a user. The back-end is built using Expressjs 4 and the cookie store utilizes redis. I am puzzled ...

Issue with AngularJS: UI Router failing to show the template

I have set up the ui.router with xhtml templates. However, the template that I configured is not showing up. app.js ClaimsDB.config(function($stateProvider, $urlRouterProvider){ $urlRouterProvider.otherwise("/main"); $stateProvider .state('main& ...

A guide on extracting certain fields and values from a JSON structure

I received a JSON output from the response body that contains various details about a contract. My goal is to extract only two specific pieces of information: "contractId" "contractStatus" To achieve this, I'm utilizing JavaScri ...