"Guidelines for inserting an image from user input into a HTML div

I am trying to dynamically add input file images to separate divs on an HTML page without using get element by class name. Each div should have a unique image associated with it instead of adding the same image to all divs with the same class. Can anyone provide some guidance or assistance with this? Thank you.

Currently, the code I have adds the same image to all divs with the specified class, but I need each div to have its own exclusive image.

Additional information: I am creating a new div each time and I want to assign a distinct image to each div that I create.

Below is the complete code for creating a new div and adding a picture:

mainspan.onclick = () => { // mainspan is button used to create div

let div = document.createElement("div");
div.classList.add("main-dd"); let button = document.createElement("button"); let img = document.createElement("img"); img.classList.add("currentimg");
div.appendChild(img); button.classList.add("btnaddinfo");
button.innerHTML = "Add item"; button.addEventListener("click", () => { addinfo.style.display = "block"; // the menu to add the new picture }); div.appendChild(button);

const uploadPictureButton = document.querySelector(".photo-upload");

uploadPictureButton.addEventListener("change", function () { displayPicture(this); });

function displayPicture(input) { if (input.files && input.files[0]) { var reader = new FileReader();

  reader.onload = function (e) {
    document
      .querySelector(".currentimg")
      .setAttribute("src", e.target.result);
  };

  reader.readAsDataURL(input.files[0]);
}   } }; })
document.querySelector(".photo-upload");   
uploadPictureButton.addEventListener("change", function () {
              displayPicture(this); }); let a; function displayPicture(input) {   if (input.files && input.files[0]) {
    var reader = new FileReader();

    reader.onload = function (e) {
      document
        .querySelector(".currentimg")
        .setAttribute("src", e.target.result);
    };

              reader.readAsDataURL(input.files[0]);

  } }

Answer №1

If you're looking to utilize the URL.createObjectURL function, you can do so with the following code snippet:

document.querySelector("input").addEventListener("change",event=>{
  document.querySelector("img").src = URL.createObjectURL(event.target.files[0]);
})
body {
  display: grid;
  grid: 1fr 1fr / 1fr;
}

img {
  width:4em;
  height: 4em;
}
<input type="file"  accept="image/png, image/jpeg"/>
<img/>

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

problems with hovering over radio buttons in Internet Explorer 9

Encountering a curious issue in IE9: When hovering over my top level wrapper div, the first radio button seems to be triggered as though it's being hovered over. This means that even if the last radio input is selected, clicking anywhere within the wr ...

The combination of Grunt and Babel runs smoothly, but fails to produce any results

I'm fairly new to the world of grunt and npm. After diving into the documentation, I managed to create my own package.json and a Gruntfile.js. This is how my directory structure looks: / |- src |- myfile.es6 |- anotherfile.es6 |- etc. |- ...

What is the best way to create transitions for item entry and exit in ReactJS without relying on external libraries?

I am looking to create an animation for a toast notification that appears when a user clicks on a button, all without the use of external libraries. The animation successfully triggers when the toast enters the screen upon clicking the button. However, I e ...

Access to PHP script (IF) unattainable following a POST occurrence

I'm completely new at this. I am attempting to create a contact form using HTML5 and PHP mail function, but I am facing an issue with my form action pointing to contacto.php. After submitting the form, it seems to be skipping over the IF condition wi ...

Textarea is limited to resizing just one specific area

I've been experiencing issues with my textareas. The problem arises when I try to have multiple textareas that need to resize on page load. It seems to work well for the first textarea, but as soon as I insert another one, only the first one responds ...

The authentication for npm failed with a 401 error code when attempting to log in

When attempting to sign in to npm using the command npm login and providing my username, password, and email, I am encountering the following error message: The Registry is returning a 401 status code for the PUT request. Even though I have used the sa ...

Exploring TypeScript: Optional Sub-Properties

I've been exploring ways to create a type-alias with properties like "answer" that I came across in this post by another user (Typescript interface optional properties depending on other property). Here's an example: type Sample = { key1: true, ...

React: The getDerivedStateFromProps method does not allow the invocation of functions

I can't seem to figure out why I keep getting a TypeError - Cannot read property 'getTodosList' of null when trying to call the getTodosList function inside the getDerivedStateFromProps method. Furthermore, after implementing the getDerived ...

provide an element reference as an argument to a directive

I am trying to figure out how to pass an element reference to a directive. I know that I can get the reference of the element where the directive is applied using private _elemRef: ElementRef but my goal is to pass the reference of another element to the ...

Angular directive dilemma

Angular is causing some issues for me as I am a beginner in using it. Below is the JSON data that I am dealing with: [ { "name":"43", "values":{ "audio":"Audio Only", "low":"Low Bandwidth", "medium":"Medium Bandw ...

The event calendar feature in Codeigniter seems to only display one item of content at a time

I am encountering an issue with the event calendar where only 1 result is being displayed even though I have multiple exams scheduled on the same day that need to be shown. My query is fetching all the exams scheduled for the same day, however, it is not ...

Enhance your JavaScript code by using the powerful Node.js util.format() method

I have been attempting to enhance the functionality of the node.js util.format function by allowing it to be used as a prototype (for example: "Hello %s".format("World")). Unfortunately, my attempts have all failed. I've tried different formats like: ...

How can parameters be sent without using the .jshintrc file with the gulp-jshint package?

Currently in the process of transitioning a grunt project to a gulp project. In the existing gruntfile, there is a section for the jshint task that looks like this: jshint: { options: { trailing:true, evil:false, indent:4, ...

Tips for setting up offline alerts using a progressive web application

I have been working on implementing reminder notifications for my progressive web app, which was originally built as a Nextjs site. The specific criteria I need to meet are: Functionality even when the device is offline Accurate notifications within secon ...

What significance does it hold for Mocha's `before()` if the function passed requires parameters or not?

In one part of my code, I have a describe block with before(a) inside. The function a originally looks like this: function a() { return chai.request(app) ... .then(res => { res.blah.should.blah; return Promise.resolve(); }); ...

Submitting forms using AJAX in Django

I am getting a 'Not Ajax' response every time I try to submit my form. There must be something small that I'm overlooking... class VideoLikeView(View): def post(self, request): if request.is_ajax(): message = 'Aj ...

Issue: ArrayBuffer failing to function properly in conjunction with Float64Array in NodeJS

Having some trouble with getting a Float64Array to work with an array buffer in Node. Here's what I've tried... var ab = new ArrayBuffer(buffer.length); var view = new Uint8Array(ab); console.log(view.length);//prints 3204 However, when I try ...

I'm encountering a RangeError in nextjs when trying to pass props to a child component

I'm a beginner with Next.js. I've been attempting to pass props to a child component that is a response from an API call. However, every time I try to add the props in the child component, I encounter a RangeError: Maximum call stack size exceed ...

I am attempting to display films within a watchlist module, however it is not allowing me to do so

I have developed a small movie database and need to showcase movies on my watchlist. While I am able to search for movies, adding them to my watchlist is only reflected in the Homescreen component and not in the WatchList component. This is the current s ...

Is it possible for a prop to change dynamically?

I am currently developing a component that is responsible for receiving data through a prop, making modifications to that data, and then emitting it back to the parent (as well as watching for changes). Is it possible for a prop to be reactive? If not, wh ...