jQuery and CSS3 for importing and customizing text files

I successfully customized the file input utilizing jQuery and CSS3.

However, there is one aspect I couldn't quite figure out. After the user selects an image or file, I want to display the selected file's text at the very bottom of the text like this:

https://i.stack.imgur.com/7RLgv.png

Here are my current codes. This is the HTML:

 <div class="container-avatar">
                    <div class="avatar-upload">
                      <div class="avatar-edit">
                        <input accept=".png, .jpg, .jpeg" id="imageUpload" type='file'> <label for="imageUpload"></label>
                      </div>
                      <div class="avatar-preview">
                        <div id="imagePreview" style="background-image: url('http://softorius.ro/images/about1.jpg');"></div>
                      </div>
                    </div>

This is the CSS:

.container-avatar {
  max-width: 115px;
  margin: 0px auto;
}

.avatar-upload {
  position: relative;
  max-width: 200px;
  margin: 10px auto;
}

.avatar-upload .avatar-edit {
  position: absolute;
  right: 12px;
  z-index: 1;
  top: 10px;
}

.avatar-upload .avatar-edit input {
  display: none;
}
...

And here is the jQuery snippet:

 function readURL(input) {
     if (input.files && input.files[0]) {
         var reader = new FileReader();
         reader.onload = function(e) {
             $('#imagePreview').css('background-image', 'url('+e.target.result +')');
             $('#imagePreview').hide();
             $('#imagePreview').fadeIn(650);
         }
         reader.readAsDataURL(input.files[0]);
     }
  }
  $("#imageUpload").change(function() {
     readURL(this);
  });

You can also view all the code on JSFIDDLE: https://jsfiddle.net/wtvrzj91/1/

Answer №1

Learning this technique is quite simple, especially since you are already accessing the file data:

https://example.com/image.png

To retrieve the name, simply access the name property: input.files[0].name. To display it, create a div and use JavaScript to insert the string into that div, like so:

HTML:

<div class="imageTitle"></div>

JavaScript (within the readURL function):

document.querySelector(".imageTitle").innerHTML = input.files[0].name;

Answer №2

To display the file name text at the bottom of the selected image area, you can make some adjustments to your CSS code. In order to comply with Safari browser instructions, instead of using display:none for (input[type="file"]), you can use opacity:0. I have positioned the edit icon in the center of a circular div, and placed the input[type="file"] inside a label element so that you can now easily drag and drop an image file onto the edit icon area.

I have also successfully tested the drag-n-drop functionality and it is working as expected.

function readURL(input) {
 if (input.files && input.files[0]) {
   var reader = new FileReader();
   reader.onload = function(e) {
$('#imagePreview').css('background-image', 'url('+e.target.result +')');
$('#imagePreview').hide().fadeIn(650);
   }
   reader.readAsDataURL(input.files[0]);
   $('.imageFilename').html(input.files[0].name).attr('title', input.files[0].name);
 }
}
$("#imageUpload").change(function() {
 readURL(this);
});
.container-avatar {
  max-width: 115px;
  margin: 0px auto;
}
.avatar-upload {
  position: relative;
  max-width: 200px;
  margin: 10px auto;
}
.avatar-upload .avatar-edit {
  position: absolute;
  right: 12px;
  z-index: 1;
  top: 10px;
}
.avatar-upload .avatar-edit label{
  display: flex;
  justify-content: center;
  align-items: center;
  width: 34px;
  height: 34px;
  margin-bottom: 0;
  border-radius: 100%;
  background: #FFFFFF;
  border: 1px solid transparent;
  box-shadow: 0px 2px 4px 0px rgba(0, 0, 0, 0.12);
  cursor: pointer;
  font-weight: normal;
  transition: all 0.2s ease-in-out;
}
.avatar-upload .avatar-edit input{
position: absolute;
  opacity: 0;
  z-index: 1;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
}
.avatar-upload .avatar-edit label:hover {
  background: #fff;
  border-color: #d6d6d6;
}
.avatar-upload .avatar-edit label:after{
  content: "\f040";
  font-family: 'FontAwesome';
  color: #007BFF;
}
.avatar-upload .avatar-preview {
  width: 100px;
  height: 100px;
  position: relative;
  border-radius: 100%;
  border: 6px solid #F8F8F8;
  box-shadow: 0px 2px 4px 0px rgba(0, 0, 0, 0.1);
}
.avatar-upload .avatar-preview>div {
  width: 100%;
  height: 100%;
  border-radius: 100%;
  background-size: cover;
  background-repeat: no-repeat;
  background-position: center;
}
.imageFilename{
text-align: center;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<br><br>

<div class="container-avatar">
  <div class="avatar-upload">
    <div class="avatar-edit">
      <label title="Upload Image"><input accept=".png, .jpg, .jpeg" id="imageUpload" type='file'></label>
    </div>
    <div class="avatar-preview">
      <div id="imagePreview" style="background-image: url('http://softorius.ro/images/about1.jpg');"></div>
    </div>
  </div>
  <div class="imageFilename"></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

Guide on adding a post type via the command line: Issue encountered - Anticipated POST console HTML error

Facing Error: EXPECTED POST in JQuery Ajax Call Encountering the same issue as mentioned in the provided link. The need is to switch from GET to POST, but direct alteration of ajax code is not feasible. It must be done dynamically using JavaScript through ...

Creating a Dynamic Tree View Component in AngularJS Using JSON Data

I am new to AngularJS and I need help creating a TreeView Structure from a JSON Object. Here is an example of my Return JSON Object: var categoryTree = [{Name:'Item1', Childnodes : {}, id: 1}, {Name:'Item2', Childnod ...

Tips for making search results stand out

Hey there! I've got a search function set up to look for keywords in a database. I'm interested in highlighting those keywords and found a second function that I want to integrate into my search function. This is the current code for the search: ...

What is the designated destination for JWT Tokens?

For my user login/signup process, I'm utilizing JWT and have a query regarding how the token is transmitted. At present, I am saving the token as a property in a JSON object on the server side, then passing it to the front-end. Upon receiving the obj ...

How can you use the parent class in jQuery to dynamically remove a specified class from all child elements

I need assistance removing classes named test1 that are children of the intro class. I have attempted a solution, but it does not seem to be working as intended. <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com ...

Node.js: The choice between returning the original Promise or creating a new Promise instance

Currently, I am in the process of refactoring a codebase that heavily relies on Promises. One approach I am considering is replacing the new Promise declaration with simply returning the initial Promise instead. However, I want to ensure that I am correctl ...

When you use ReactDOM.render inside a <div>, it does not instantly generate HTML code

I am currently working with React version 16.7 and attempting to embed React components into a third-party JavaScript library (specifically, Highcharts) that requires me to output HTML from a function. This is the approach I am taking at the moment: funct ...

Using React Refs to Trigger the video.play() Method - A Step-by-Step Guide

Is there a way to use a ref in order to trigger video.play()? Currently encountering an error: preview.bundle.js:261916 Uncaught TypeError: _this2.videoRef.play is not a function Take a look at my component: import React from 'react'; import s ...

KineticJs: Enhancing Rotation with Multitouch Capability

Currently, I have a click event implemented in my code that rotates my puzzle piece by 90 degrees when clicked. However, I would like to change it from a mouse click to a touch event. How can I achieve this? Thank you. piecesArray[i][j].shape.on("mous ...

numbered navigation jquery plugin

Can anyone recommend a jQuery plugin or alternative solution for creating a navigation system for comments similar to YouTube? Here is the link for reference: Thank you in advance. ...

Title: How to Build a Dynamic Logo Carousel with React and CSS without External Dependencies

Currently, I am in the process of integrating a logo carousel into my React web application using CSS. My goal is to create a slider that loops infinitely, with the last logo seamlessly transitioning to the first logo and continuing this cycle indefinitely ...

What is the best way to create a highlighted navigation bar using Angular 2?

Is there a way to keep the navbar active even after refreshing the page in Angular 2? I am currently using CSS to accomplish this, but the active tab is removed upon page refresh. Any suggestions on how to tackle this? HTML:-- <ul class="nav navbar- ...

Hover your mouse over the menu to activate a timeout feature

Having an issue with my multi-level menu - when I hover over a main menu item, the sub-menu items are supposed to display. However, if I move the mouse too quickly from the main item to the sub-item and it goes off the path, the sub-menu disappears and I h ...

The React MUI v5 Card's background features a subtle white hue with a 5% opacity, leaving me curious about its origin

I've noticed a strange styling issue in my code. It seems to be related to a class called .css-18bsee0-MuiPaper-root-MuiCard-root, possibly from MUI's Card or MUI's Paper components. However, I can't find it in my own code. While tryin ...

How to Keep Button Highlighted After Clicking

I've experimented with various methods like using :active, :focus, adding a class, and modifying CSS rules through jQuery to maintain the button highlight, but none of them have been successful. Please take a look at my code and point out any mistakes ...

Unusual display of fonts on Chrome

Recently, I encountered a strange issue with font rendering on Chrome/Opera compared to Firefox. The problem can be seen in the preview below - pay attention to the pink text. It appears blurry initially but sharpens once text input is focused. This same i ...

Customize your radio buttons to display as stylish boxes with Bootstrap

Check out my Fiddle here... The radio buttons are displaying correctly in the fiddle. <div class="element-radio" title="Do you want to float the text to the left, right, or not at all?"><h4 class="title" style="font-weight: bold;">Float (left ...

How to retrieve an object's property within a component

Currently, my goal is to retrieve the email property from the user object {"name":"test", "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="582c3d2b2c182c3d2b2c7620">[email protected]</a>"} I want to achie ...

The structure of the figure tag for HTML5 validation

Could you please confirm if the Figure tag is correctly used in the html structure? Regarding html5 validation, can I use this structure? <a href="#"> <figure> <img src="" class="img-responsive" alt=""> <figcaption> ...

Generating Speech from Text using jQuery API in HTML

Can a website be created to detect textbox text upon longClick by the user, and function across various browsers? The site should also have mobile compatibility. Appreciate any help! ...