How can I make an image the background on a webpage when clicking the mouse?

I find myself in a predicament without any code to guide me. The idea seems simple - I desire the ability to select an image from a collection and set it as the background image for the webpage.

While I understand that JavaScript is essential for this task, I am uncertain of the initial steps to take.

Initially, I considered defining an array in JavaScript to facilitate image selection, but then I hit a roadblock on how to implement the functionality where clicking on a specific image changes the background image.

Answer №1

If you want to create click handlers for your img elements to adjust the style attributes of document.body, you can do so with the following code:

for (let img of document.querySelectorAll("img")) {
    img.addEventListener("click", function() {
        document.body.style.backgroundImage = `url('${this.src}')`;
        document.body.style.backgroundRepeat = "no-repeat";
        document.body.style.backgroundSize = "cover";
    })
}
<img src="https://th.bing.com/th/id/OIP.wwxK07x0Umfnh0l-nrjxjgHaDg?pid=ImgDet&rs=1">
<img src="https://www.forestis.it/media/1064/forestis-see-idm.jpg?mode=max&rnd=132197836980000000">

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

How to remove the horizontal scrollbar from material-ui's Drawer element

My drawer is displaying a horizontal scroll, despite my efforts to prevent it. I've tried adjusting the max-width and width settings in Menu and MenuItems, as well as using box-sizing: border-box. I also attempted setting overflow: hidden on the Drawe ...

Can a ng-repeat value be assigned to a text input field?

<tr ng-repeat="person in users" ng-class="{'chosen': person.AdmissionID == currentSelection}" ng-click="selectRow(person.AdmissionID)"> <td>{{person.AdmissionID}}</td> <td>{{person.AdmissionNumber}}</td> ...

Access data from JSON array in Angular 2

I'm facing a basic issue here. I have a JSON file named pageDefinition.json that is being loaded into my component. Here's how the JSON data looks: ... "testArray": [ {"id": 0, "name": "row1"}, {"id": 1, "name": "row2"}, {"id": 2, "n ...

Discover how ReactJS can dynamically display or hide div elements based on specific conditions being met within JSON data

How do I show or hide a div based on a condition in React, using data from a JSON array? I have implemented the code below, but changing the value of isPassed={resultPass.pass} to isPassed={resultPass.failed} still displays the result as pass. I came acro ...

Adjusting the array of buttons with various functions within the Header component

I am looking to create a customizable Header component with different sets of buttons that trigger various functions. For example, on the home page, the buttons could be "visit about page" and "trigger vuex action A", while on the about page they could be ...

Why is the last move of the previous player not displayed in this game of tic tac toe?

Why does the last move of the previous player not show up in this tic-tac-toe game? When it's the final turn, the square remains empty with neither an "O" nor an "X". What could be causing this issue? Here is the code snippet: The HTML code: <div ...

The checkbox is not showing the check mark accurately

I am currently working on a React form where I am trying to retrieve the status of a checkbox element from local storage using the useEffect hook. const [checkbox, setCheckbox] = useState(false); useEffect(() => { setCheckbox(localStorage.getItem(&ap ...

Cross-Origin Resource Sharing using Express.js and Angular2

Currently, I am attempting to download a PLY file from my Express.js server to my Angular/Ionic application which is currently hosted on Amazon AWS. Here is the Typescript code snippet from my Ionic app: //this.currentPlyFile contains the entire URL docum ...

Building a stylish bootstrap button within the cell rows of a table using jquery

I need to insert a button in the "Details" column. <button class="btn btn-primary btn-fab btn-icon btn-round"> Here is my code: var tableRef = document.getElementById('ticker_table').getElementsByTagName('tbody')[0]; var ti ...

Is it possible to access forms and input fields in an AngularJS script without having to pass them from the HTML code?

Seeking a solution for input field validation, I have written code where input field states are passed from HTML to a script through a function. However, my goal is to directly retrieve the values in the script without passing them from the HTML when calli ...

Utilizing numerous occurrences of my personalized Angular JS Directive within the identical form

I've been struggling to find a solution for this particular issue. On my webpage, I have two instances of a directive that are supposed to set values for two different text fields. However, when I select one value, the other field automatically chang ...

How can I stop the setinterval function in JavaScript?

My issue revolves around intervals. Upon declaring a function with setInterval, I find that even after clearing the interval, the function continues to execute. Here is my code: if (score == 1) { leftBlinkTimer(0) } else if (score == 0) { leftBlin ...

Populate an AngularJS select dropdown with JSON data and automatically pre-select the specified value

I am currently dealing with 2 entities: project and project_types. Each project can have one or multiple project_types associated with it. Using ajax (ng-init), I am retrieving the project data (including its related project_types) and all available proje ...

Issue: Infinite loops detected in AJAX functions

I am using $.get methods in the following code snippet: $.get("/url" , function(z) { var a = $(z).find("span"); for (var i = 0 ; i<a.length; i++){ var v = $(a).eq(i).children("strong:first").text(); alert(v); } }); However, the s ...

Displaying a div upon hovering over another div is resulting in numerous server requests and a flickering effect

I am attempting to create a hover effect where one div floats next to another. The layout of the divs is like a grid, placed side by side. Check out my code on this fiddle. Using plain JavaScript, I want to display a second div (div2) floating next to div ...

Isolating Express.js Requests for Enhanced Security

In my Node.js Express app, multiple users send requests to the server for various actions such as earning points, changing email addresses, and interacting with other users. My server code utilizes several setTimeouts, leading me to question whether diffe ...

Setting MUI input value within a loop using an array value in React JS: A step-by-step guide

Recently, I created a React js demo using React MUI. To handle inputs, I created a separate component called InputText.js for each input field. The issue I encountered is when I tried to use this component to display multiple education fields stored in an ...

Transferring information from various HTML forms using JQuery's ajax functionality

Hello there! I have recently started learning how to use jQuery AJAX for file uploads. Currently, I am working with a simple HTML form and including JavaScript/jQuery code within it to make an AJAX request. <!DOCTYPE HTML> <html> <head> ...

Having trouble retrieving the table value from an HTML document?

I am trying to retrieve specific information from this source: https://i.sstatic.net/g1wDj.png This information is crucial for fetching data from a database using a primary key. However, extracting this value has proven to be quite challenging. Upon docu ...

What steps should I take to grant API access if cross-browser requests are restricted?

Creating a C# web service to retrieve data from a server raises the question of how to grant API access to other users who want to query it using client-side code. For example, imagine the web service is hosted on Domain1.com. How can someone from Domain2 ...