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

React, Redux, Thunk - the trifecta of powerful

After spending a considerable amount of time struggling with this particular piece of code, I have scoured online resources such as Stack Overflow and the documentation, but there is still something that eludes me... The code in question revolves around t ...

Fastify route handler failing to start after onRequest hook is executed

I am currently working on a fastify application that needs to capture the raw body of post requests for authentication purposes. After extensive research, I discovered that fastify does not have native support for this feature. The solutions I found online ...

Tips for utilizing useQuery when props change using Apollo:

I am currently facing a challenge with my BooksList component where I need to pass props down to the BooksDetails component only when a title is clicked. I am trying to figure out how to utilize an Apollo hook to query only on prop changes. I have been ex ...

The use of anonymous arrow functions results in Fast Refresh not maintaining local component state

I am facing an issue with the code in my pages/index.js file: import React from 'react'; import dynamic from 'next/dynamic'; const TVChartContainer = dynamic( () => import('../components/TVChartContainer').then ...

Using a twig loop to display just a single table cell

The following twig loop is used to generate data: {% for reservationDate, rooms in data.pricingTable %} <tr> <td> {% for room in rooms %} <tr> <td ...

Styling a parent element when it is in focus using CSS3

Is there a way to apply a style to the parent element when an input is in focus? input:focus { background-color:yellow; } For example, if we have the following HTML: <div class="foo"> <input type="text /> Hello </div> I ...

Utilizing jQuery to select an attribute containing a special character

There is a special div with a unique data-id: <div data-id=""> </div> I tried to target this div using jQuery, but it didn't work as expected: jQuery("[data-id='']").text('hello'); Can anyone help me on how to ...

Getting rid of unnecessary compiled CSS files in Compass

After making changes to files and running compass compile, the compiled files remain even if they are renamed or deleted. Similarly, compass clean does not remove these old files as it only focuses on cleaning up current files in use. I want to avoid compl ...

Troubleshooting Angular 2 Fallback Route Failure

My current project is using Angular 2 Webpack Starter but I am having trouble with the fallback route. In my app.routes.ts file, I have defined the routes as follows: import { Routes } from '@angular/router'; import { HomeComponent } from &apos ...

How to Calculate the Time Interval Between Two CORS Requests Using jQuery AJAX

When using jQuery's $.ajax to make a CORS request to a web service, there is typically a pre-flight request followed by the actual POST request. I have observed that when there is a time gap between making two web service calls, both a pre-flight and ...

Is there a way to make divs expand on top of existing content when hovering over them, in order to avoid needing to scroll through overflow content? I am currently working with

I am working with 9 boxes contained within divs, each box includes data that exceeds the size of the box itself (represented by Some Text repeated for demonstration purposes). I am seeking a solution where hovering over any box will cause it to enlarge and ...

Position validation in jQuery is crucial for ensuring that form

After attempting to implement the jquery validate plugin by following the example provided at http://docs.jquery.com/Plugins/Validation, I have encountered some challenges in my own code. The issue lies in determining where to call the validation function. ...

Angular UI-Router: Difficulty in Child State Accessing Parent Controller

I am currently using ui.router's nested views feature in my Angular application. Here is the relevant part of my .config: $urlRouterProvider.otherwise('/'); $stateProvider .state('home', { url: '/', templateUrl: ...

How to change elements within an HTML string using jQuery

I am facing an issue where I have an HTML string (not DOM) that needs to be manipulated using jQuery. However, the code I am trying does not seem to work as expected: var html = '<div><h4><a class="preview-target" href="content.html"&g ...

Launch a new window with the window.open() method and execute a function on the newly opened window

I am having trouble generating a barcode in a new window using the barcode generator script. Despite trying to use window.focus(), I can't get the barcode to appear in the new window. Any assistance on how to generate the barcode in a separate window ...

Utilizing constants within if statements in JavaScript/TypeScript

When working with PHP, it is common practice to declare variables inside if statement parenthesis like so: if ($myvar = myfunction()) { // perform actions using $myvar } Is there an equivalent approach in JavaScript or TypeScript?: if (const myvar = myf ...

Coding in PHP, JavaScript, and HTML allows builders

I am facing some difficulties in locating my specific question, so I will describe it here. Currently, I am working with an oracle database and integrating it into an HTML website using javascript and php. I have successfully displayed the php file, but th ...

Retrieve a string value in Next.JS without using quotation marks

Using .send rather than .json solved the problem, thank you I have an API in next.js and I need a response without Quote Marks. Currently, the response in the browser includes "value", but I only want value. This is my current endpoint: export ...

Is the POST AJAX request being rejected due to CORS restrictions?

I have configured CORS on my node.js server running on port 5000 in the following way: var app = express(); app.use(cors()); //normal CORS app.options('*', cors()); //preflight app.post('/connect', function(req, res) { console ...

What is the best way to transfer the value of a slider from jQuery or JavaScript to a Python Flask application

Trying to implement a round slider that displays its value on the client-side webpage. Whenever the user adjusts the slider, the updated value needs to be sent to the server using Python Flask as the backend. I attempted to achieve this using jQuery and Aj ...