Guide to showcasing an image that has been uploaded by me

I have created a button that allows users to input an image, but I am struggling to display the picture on the screen. I tried creating an empty `img` element and changing its URL based on what I saw on another website, but it was not successful.

  • Here is the HTML code:

    <input 
                         id="myImage"
                         class="photo-upload"
                         type="file"
                         accept="image/*, image/jpeg">
    
                         <img id="the-picture" width="200" />
                    
                
  • And here is the JavaScript code:

    const uploadPictureButton = document.querySelector(".photo-upload");
    
                         uploadPictureButton.addEventListener("click", displayPicture);
    
                         function displayPicture(event) {
                             let image = document.getElementById("myImage");
                             image.src = URL.createObjectURL(event.target.files[0]);
                         };
                    
                

Answer №1

The code needed some adjustments to read the file and generate a URL. Below is the corrected snippet for the code:

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.getElementById('the-picture').setAttribute('src', e.target.result);
    };

    reader.readAsDataURL(input.files[0]);
  }
 }
 <input 
     id="myImage"
     class="photo-upload"
     type="file"
     accept="image/*, image/jpeg">

<img id="the-picture" width="200" /> 

Answer №2

To showcase an image, consider utilizing the innerHTML method.

Answer №3

This solution has been quite effective for me

<img height="100" width="100" alt="profile picture" id="previewImage"> <input type="file" onchange="document.querySelector("#previewImage").src = window.URL.createObjectURL(this.files[0])">

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

Surprising Behavior of React's OnClick Event

Custom Component function ProductCard ({image, name, stats, id}){ let dispatch = useDispatch() let quantity = 1 return ( <> <div className="product-card" ...

Creating a customizable React application with an extra environmental setting

I'm currently working on an app that requires some variations. While the core remains the same, I need to customize certain parts of the app such as color schemes and images. My inquiry is: Is it feasible to construct an app with a specified instance ...

Ensure that the button click is validated repeatedly until it becomes disabled by utilizing

Seeking assistance with validating a button click using Cypress. The goal is to ensure the button is clickable only when slides are available. If no slides are present, the button should be disabled by adding a disabled class. Any recommendations for impro ...

What is the reason behind Firefox opting for a 2x image while Chrome goes for a 1x image when the devicePixelRatio is 1

When deciding between 1x and 2x options: Firefox will opt for 2x if devicePixelRatio is less than 1 Chromium will choose 2x if devicePixelRatio is less than 1.5 Testing this in Safari is tricky as devicePixelRatio remains constant even when scaling t ...

Bootstrap Carousel is unable to display any items as the count returns zero

I'm having trouble determining the total number of items in a Bootstrap carousel, as my code consistently returns 0: var totalItems = $('.carousel-item').length; The data-ride attribute is specified in the parent div: <div id="carous ...

What is the process for transferring the value from a list item to the search field box?

I have developed a Bootstrap/jQuery function that can display the item matching the user's search query. However, I am facing some challenges in making the selected item populate the search field or providing clear validation to the user once it is ch ...

Tips for adding information into IndexedDB after receiving an AJAX response:

If I were to start by setting up the database outside of my Ajax call like this: // This code is compatible with all devices and browsers, utilizing IndexedDBShim as a last resort var indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitInd ...

Looking to adjust the title font size when exporting DataTable to Excel?

Would like to customize the title of an excel file exported from Datatable. I attempted to implement a solution found on a stackoverflow post, but it ended up applying the customization to the entire sheet. $("#datatable").DataTable({ ...

What causes reCaptcha to vanish when I switch to a different page?

When trying to load the captcha by clicking the refresh button, it works fine. However, if I navigate to another page and then click the browser's back button, the captcha disappears. How can this issue be resolved so that the captcha is always shown, ...

Modify the information within several div sections

Is there a way to update the content inside two divs simultaneously when a button is clicked? Specifically, I want to change the bio in one div and the picture in another based on the selected player. Currently, when the button is pressed, it only loads th ...

How can I make the row color of a jQuery datatable change when the row is selected?

One of my challenges involves implementing a jquery dataTable (view here) where each row contains a checkbox. I want the row's color to change when the checkbox is checked. This is the approach I attempted: <table id="tabellaOrdinaFarmaci" class=" ...

What is the best way to utilize regex to replace two elements simultaneously?

I am facing a challenge with manipulating a string of characters by adding span tags to highlight specific words and change their color. While I have successfully implemented the changes for one pattern using regex, I'm struggling to do the same for a ...

Tips to avoid multiple HTTP requests being sent simultaneously

I have a collection of objects that requires triggering asynchronous requests for each object. However, I want to limit the number of simultaneous requests running at once. Additionally, it would be beneficial to have a single point of synchronization afte ...

Adding images in ascending order according to the parent div's ID

If I have three different divs with unique IDs on a webpage <div id="product-id-001"></div> <div id="product-id-002"></div> <div id="product-id-003"></div> Is there a way to add image elements based on the ID of each d ...

Ways to make nodejs return a different value instead of an object promise

Within my user.js file, I have an async function designed to retrieve the avatar's location from the database. The code for this operation is as follows: async findavatar(username) { const sql = `SELECT image FROM users WHERE user = "${userna ...

What is the reason behind the fact that the "transform" property of document.getElementById().style.transform="translateX()" only translates the element once?

I'm currently in the process of developing a new online game. With just a simple click of a button, my goal is to have the red square move horizontally by 50 pixels. Here's a snippet of the HTML code: <!DOCTYPE html> <html> <hea ...

JQuery's addClass function is not functioning properly

Check out the code snippet below: function toggleAccessRequests() { var buttonValue = $("#showAccessRequests").val(); if (buttonValue == "Show") { $(".hideAccessRequest").removeClass("hideAccessRequest"); $("#showAccessRequests").v ...

Oops! Looks like we have encountered an issue with reading the property 'checked' of nothing

Whenever I click the checkbox, an image should be displayed. Unfortunately, I encountered an error: Uncaught TypeError: Cannot read property 'checked' of null at (index):185 at dispatch (VM576 jquery.min.js:3) at i (VM5 ...

"Send the response in ExpressJS before making a request to loop through the

I am currently working with a postgres database that contains records with a column format in JSON, which refers to other similar records. The challenge I am facing is retrieving linked records through asynchronous methods due to the nested structure and ...

Extracting responseXML data specifically for CSS styling purposes

I am working on a simple XMLHttpRequest setup that fetches data from an xml file and displays it in a div on my webpage within a ul element: var requestData; if (window.XMLHttpRequest){ requestData = new XMLHttpRequest(); }else{ requestData = new ...