Retrieving an image from an input file and setting it as the background of a div element

I am currently developing a whack the mole game using Vanilla JS, and I'm attempting to allow players to choose their own target by uploading an image file. However, despite days of searching for a solution, I have not been successful.

HTML:

<input type='file' id='getval' name="background-image" />

<div class="game">
 <div class="hole hole1">
    <img class="mole">
 </div>
 <div class="hole hole2">
    <img class="mole">
 </div>
</div>

Javascript Vanilla:

document.getElementById('getval').addEventListener('change', readURL);
function readURL() {
  let file = document.getElementById("getval").files[0];
  document.getElementsByClassName('mole')[0].setAttribute("style", "background-image: url(" + file + ")");
  }

CSS:

.mole {
  background-image: url('');
}

The game functions properly, but the uploaded image does not display correctly:

https://i.sstatic.net/RkezK.png

If anyone has any insight on how to resolve this issue, I would greatly appreciate it.

This project is part of #javascript30. I modify these projects to practice using Vanilla JS, but I've hit a roadblock with this one.

Answer №1

Here is how you can achieve that:

https://www.example.com/javascript/file-and-filereader-tutorial

const fileInput = document.getElementById('imageInput');

const images =  document.querySelectorAll('.mole');

fileInput.addEventListener('change', (e) =>{
    const file = e.target.files[0];

    let fileReader = new FileReader();
    fileReader.readAsDataURL(file);
    fileReader.onload = function (){
        images[0].setAttribute('src', fileReader.result);
        // images[0].setAttribute('style', `background-image: url('${fileReader.result}')`);
    }
})
body {
  min-height: 100vh;
  margin: 0;
  background-color: bisque;
  display: grid;
  place-content: center;
}

.box{
  display: flex;
  flex-direction: column;
  place-content: center;
  align-items: center;
}

input{
  margin-bottom: 1rem;
}

.images{
  display: flex;
  flex-direction: row;
}

.mole {
  width: 10rem;
  height: 10rem;
  margin-bottom: 1rem;
}
<div class="box">
    <input type="file" id="imageInput" />
    <div class="images">
      <img class="mole" />
      <img class="mole" />
    </div>
  </div>

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

Whenever I adjust the zoom on my HTML page, it either scrolls upwards or downwards

Is there a way to prevent the page from scrolling when using zoom-in or zoom-out? I attempted using overflow: hidden in the body, but it did not work. <!DOCTYPE html> <html lang="en"> <head> <meta charset=&q ...

Navigating to the present child state with modified parameters can be achieved using the following steps

Check out this demo: https://jsfiddle.net/explorer/622qzqsc/ In the platform I'm working on, we have an advanced concept of state management, specifically for building timelines. In the template of this system, there's a code snippet (which is c ...

Utilize Bootstrap's custom validation exclusively on fields that are invalid

Exploring Bootstrap features has led me to wonder if there's a straightforward method to change the styling of a field specifically when it is considered invalid. <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" ...

Currently, I am in the process of constructing a DSpace repository on an Ubuntu 16.04

I have successfully set up a DSpace repository on Ubuntu 16.04 LTS by following the installation instructions provided in this manual. After deploying the webapps, I encountered an issue when trying to add new items. Upon clicking the search link, I recei ...

Updating parameter value upon the execution of an internal function in Javascript

How can I log the text from a textbox to the console when a button is clicked in this code snippet? <body> <input type="text" id="ttb_text" /> <script type="text/javascript"> function AppendButton() { var _text = ''; ...

What are some ways to eliminate the excess white space beneath the footer in HTML?

After creating a responsive webpage that works flawlessly on mobile devices and tablets, I noticed a problem with the footer when viewed on desktop. There is an empty white space at the end of the webpage, and upon inspecting the browser, it focuses on the ...

Parallax Effect Slows Down When Scrolling In Web Page

Currently in the process of creating a website with a scrolling parallax effect using Stellar.js on the header and three other sections. However, I'm experiencing lag when scrolling, especially at the top of the page. I've attempted to reduce la ...

Template is not populating with data (Angular)

Currently, I am honing my Angular skills by working on a simple project. I have been seeking answers to my queries on Stack Overflow as they closely align with the issue I am facing. My challenge lies in displaying asynchronous data before it is initialize ...

Why isn't changing the property of a Sequelize instance having any effect?

While I've successfully used the standard instance syntax in the past, I'm facing a challenge with updating an instance retrieved from the database in this specific section of my code. ... const userInstance = await db.models.Users.findOne({wher ...

Adaptable Bootstrap navigation bar

In the process of creating a responsive menu, I have designed a navbar for desktop that includes 3 text links and 3 small pictures that are also links. However, when transitioning to a smaller screen size, my goal is to keep the 3 small pictures as they a ...

Tips for creating a header.php and footer.php integrated with CSS files

I am in the process of constructing my website using HTML files. I want to make sure that my header and footer sections are dynamic so I can easily modify them without having to update numerous files each time. While I've attempted a few methods based ...

Failure to trigger a follow-up function in webSQL transaction's success callback

Review the code below. I have called setQuestion() within the successCallBack of db.transaction but am encountering an error: Uncaught TypeError: this.setQuestions is not a function. Can you spot any issues in my code? game.module( "game.scenes.scene" ) ...

The ZK Component fails to display within the HTML tag

In my dilemma, I am attempting to showcase a hyperlink component under an HTML tag along with some instructions for click functionality: <zk> <html> <a label="show me" onClick="@command('showMe')" /> </html> </zk ...

Has a newly created element been styled or are all values set to default since it is outside of the DOM?

First, I begin by creating an element: let link = document.createElement('a'); After my document is fully loaded and all styles and scripts are applied. The styles may look something like this: a { background-color: salmon; } Therefore, it w ...

The second AJAX call is unsuccessful

I have created a dynamic ajax website that retrieves pages from the /pages folder and displays them within an ajax-container div on my index.php. Now, I am looking to implement a second ajax request that will only be triggered on certain pages. For examp ...

What is the best method for creating a fade effect on a div background?

I am trying to animate a div with the id #test from a 0 opacity background to an opacity of 0.7 using CSS rgba values, but for some reason, the .animate function is not working as expected. Here is my CSS: #test { background-color: rgba(0, 0, 0, 0); ...

Utilizing a React Hook to set data by creating a pure function that incorporates previous data using a thorough deep comparison methodology

I have come across the following code snippet: export function CurrentUserProvider({ children }) { const [data, setData] = useState(undefined); return ( <CurrentUserContext.Provider value={{ data, setData, }} & ...

Adaptable Layouts in Bootsrap Grid

I am currently working with Bootstrap Grid. https://i.sstatic.net/giJOI.png One issue I am facing is when I switch back to my mobile screen, I want the layout to adjust accordingly like https://i.sstatic.net/RYPJm.png I have tried different methods but ...

How can I create a cube with complete beveling using Three.js?

I'm struggling to create a beveled cube in my project. I have come across the THREE.ExtrudeGeometry snippet in the documentation here. However, when I tried it out, I only managed to achieve beveled sides on the top and bottom faces like this: https: ...

Utilizing JQuery to track DIV clicks

I am encountering an issue with DIV clicks while using JQuery. I need guidance on this problem. Within my HTML, there are three designated DIV elements: <html> <body> <div id="overviewContainer"> <div id="firstContainer"></ ...