What is the best way to showcase a photo selected using an HTML input within a div container?

My goal is to select a photo from a folder and display it on a webpage, but I have struggled to find a working solution. Can this be achieved using just basic HTML, CSS, and JS? I am new to web development, so please forgive me for any beginner questions.

Below is the code I have been working with:

<!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" href="styleTake2.css">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
        <script>
            function getImage(input){
                if(input.files && input.files[0]){
                    var reader = new FileReader();

                    reader.onload = function (e) {
                        $('#placeholder')
                            .attr('src', e.target.result)
                            .width(150)
                            .height(200);
                    };
                }

                reader.readAsDataURL(input.files[0]);
            }
        </script>
    </head>
    <header>
        <img src="assets/logo.png" class="logo">
        <ul class="top-bar"> 
            <li class="top-button">
                <i class="fa fa-upload"></i> 
                <input id="uploadFile" type="file" onchange="readURL(this);" />
            </li>
            <li class="top-button">
                <i class="fa fa-save"></i>
                <button id="btnSave">Save image</button>
            </li>
        </ul>
    </header>
    <body>
        <ul class="side-bar">
            <hr width="199px" style="margin-top:0px;">
            <li class="side-button">
                <i class="fa fa-magic"></i> Effects
            </li>
            <hr width="199px">
            <li class="side-button">
                <i class="fa fa-volume-off"></i> Sounds
            </li>
            <hr width="199px">
            <li class="side-button">
                <i class="fa fa-image"></i> Select background
            </li>
            <hr width="199px">
        </ul>
        <img id="placeholder" src="#" alt="asdf" />
    </body>
</html>

I prefer to understand the code rather than blindly copying and pasting it, so I appreciate any explanations or guidance you can provide.

Answer №1

By utilizing the filereader feature:

HTML

<input type='file' onchange="readURL(this);" />
<img id="blah" src="http://placehold.it/180" alt="your image" />

CSS

img{
  max-width:180px;
}
input[type=file]{
padding:10px;
background:#2d2d2d;}

JS

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

                reader.onload = function (e) {
document.querySelector('#blah').setAttribute('src',e.target.result )

                };

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

You can view a working example on codepen here.

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

_my_custom_styles.scss are being overridden by reboot.scss

Hey there, I'm currently facing an issue where my custom CSS is getting overwritten. Even though I have placed my custom CSS beneath the CDN bootstrap reference, it doesn't seem to resolve the problem. For instance, when attempting to change the ...

How can I achieve a smooth background-image transition in Firefox?

Currently, I'm on the hunt for a substitute for this specific code snippet: "transition:background-image 1s whatever" This particular transition only seems to function on webkit browsers, leaving Firefox users out of luck. I experimented with utili ...

Can a session be prolonged by an ajax request triggered by a timer?

In my Asp.Net MVC application, I am looking to dynamically hide the cart and certain buttons when a user's session expires. I stumbled upon a solution that involves calling a function on a timer in ASP.NET MVC. Here is the reference link: How to call ...

Encountered an error loading resource: server returned a 404 status code while utilizing Angular framework and deploying via GitHub Pages

Currently facing an issue with my Angular website deployment on Github Pages, receiving a console error "Failed to load resource: the server responded with a status of 404 ()" at "home: 1". This error specifically seems to be related to the app.component ...

Enhance your AngularJS table with a custom Javascript context menu!

In the process of developing a shift planner, I have implemented a JS context menu and am attempting to display the shifts using Angular. However, upon clicking any table cell, all cells are being updated simultaneously. Is there a workaround for this issu ...

React i18next provides a fallback language in case the specified language is not

In my React app, I have implemented i18next for translating files, using the following approach: i18next.js (original) import i18next from 'i18next'; import XHR from 'i18next-xhr-backend'; import detector from 'i18next-browser-lan ...

Encountered an issue during my initial AJAX call

Hello everyone, I am currently attempting to use AJAX to send a request with a button trigger and display the response HTML file in a span area. However, I am encountering some issues and need help troubleshooting. Here is my code snippet: //ajax.php < ...

Exploring the process of transferring a variable from Frontend to Backend via a GET API in ReactJS with an Express API

When working with my freight Shipment table, I need to access the email of the logged-in user in order to perform some frontend tasks. However, I am struggling to retrieve this information using the Axios.get() method and use it to query my MySQL DB. In t ...

Executing Selenium WebDriver to interact with a hidden element

Hello, I am interested in learning how to interact with hidden elements and disable them using Selenium WebDriver. I've managed to achieve this with Selenium 1 by using the following code: selenium.click(id="idOfHiddenField"); Unfortunately, this a ...

The issue I am experiencing within my PHP code is that the redirection to the gratitude page is not functioning correctly when utilizing

As a newcomer to PHP, I have been struggling with an example code from a website that is not redirecting to the thank you page as expected. Moreover, the email functionality is not working properly either. The code was sourced from: Upon downloading the f ...

Incorrect color change on button triggered by onMouse actions and state fluctuations

While creating a user profile on my app, I encountered an issue with button coloring. When I try to add color functionality to the button, it turns red instead of green and remains red even when the mouse is not hovering over it. My goal is to have the but ...

What is the best way to update a CSS class in React JS?

Suppose I have a CSS class called 'track-your-order' in my stylesheet. Whenever a specific event occurs, I need to modify the properties of this class and apply the updated values to the same div without toggling it. The goal is to replace the ex ...

Add a Page to Your Domain Name using the Text Input Box

I'm looking to create an input field that allows users to enter a text string, which will be added to a domain name when submitted, redirecting the user to a specific page. Here's how the process works: The user enters 'foo' into the ...

The CSS styling in Internet Explorer 11 is causing cells to merge into the same column in a table

In my CSS-styled form that resembles a table, the two input elements are displaying on top of each other instead of side by side. How can I adjust them to appear next to each other? There is a possibility that this issue could be browser-specific. The for ...

Modifying the background image of div elements with JQuery in a loop function is ineffective when using Google Chrome

I am facing an issue in my application where I have a for loop to change the background image of two divs. The code snippet is as follows: for (var i = 0; i < length; i++) { $("div_" + (i + 1)).css("background-image", "../imageFile.png"); ...

IntelliJ does not support the use of newlines within Vue.js component templates

While working with Vue.js in IntelliJ IDEA, I encountered a small problem related to defining component templates. The issue is that IntelliJ seems to struggle when the template spans more than one line and attempts to concatenate them together. For examp ...

Subdomain for an Ajax request

Can we use ajax requests to extract data from and fetch information from pages like ? It appears that JavaScript still does not permit subdomain requests. ...

Exploring the world of ASP .NET development with the powerful Sonar

We're currently working on an ASP .NET project and are looking for a way to analyze JavaScript files on-the-fly. Unfortunately, SonarLint only offers analysis for C# files. The incremental analysis feature seems to have been phased out, and issues ana ...

What could be the reason for the inconsistent behavior of onClick, causing it to occasionally fail to display the associated

I just started using typescript 2 days ago, mainly to create a custom component for my streamlit app. I've made a navigation bar with a tab that can be clicked on the sidebar, but it's displaying some erratic behavior. Sometimes when I click on t ...

Loading of local resources is restricted in the Apache web server

I am encountering an issue with my Apache web server on a Raspberry Pi. I need to display graphs using the MPLD3 libraries, which are loaded from the server's folder. When I run my index.php page, I receive a Not allowed to load local resources error ...