Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

css hide "Choose File" button but display file after select

I would like to make custom button for an image upload. I am able to get this result with the demo below:

https://jsfiddle.net/algometrix/fgrbyo4z/

But HOW CAN I DISPLAY the file name selected after? Or maybe even a thumbnail of an image if possible? Like after I choose a file from the window that pops open I would like it to display 'the file name' on the page after I selected it.

Javascript - jQuery is totally an option here if anyone can help in that area.

HTML

<div>
  <div style="display:block;text-align:center;margin-top:20%;">
    <label for="files"> <span class="btn">Select Image</span></label>
    <input style="visibility: hidden; position: absolute;" id="files" class="form-control" type="file" name="files">

  </div>

</div>

CSS

.btn {
  font-family: Arial;
  color: #ffffff;
  font-size: 20px;
  background: #3f88b8;
  padding: 10px 20px 10px 20px;
  text-decoration: none;
}

.btn:hover {
  background: #3cb0fd;
  background-image: -webkit-linear-gradient(top, #3cb0fd, #3498db);
  background-image: -moz-linear-gradient(top, #3cb0fd, #3498db);
  background-image: -ms-linear-gradient(top, #3cb0fd, #3498db);
  background-image: -o-linear-gradient(top, #3cb0fd, #3498db);
  background-image: linear-gradient(to bottom, #3cb0fd, #3498db);
  text-decoration: none;
}
like image 619
Papa De Beau Avatar asked Mar 05 '16 20:03

Papa De Beau


People also ask

How do I customize my upload button?

Use a label tag and point its for attribute to the id of the default HTML file upload button. By doing this, clicking the label element in the browser toggles the default HTML file upload button (as though we clicked it directly).


2 Answers

With the addition of javascript, we can just watch for the change event on the input, and put the name on the page. Please note these minor HTML changes:

<div class="file-upload">
  <label for="upload-1" class="btn">Upload</label>
  <input type="file" id="upload-1">
  <p class="file-name">Please select a file.</p>
</div>

With this jQuery:

jQuery(function($) {
  $('input[type="file"]').change(function() {
    if ($(this).val()) {
         var filename = $(this).val();
         $(this).closest('.file-upload').find('.file-name').html(filename);
    }
  });
});

Working Fiddle

like image 87
random_user_name Avatar answered Oct 06 '22 00:10

random_user_name


Just tap into the change event of the file element:

 var file = document.getElementById("files");
 file.addEventListener("change", function(){ alert(this.value); });

Shown in this fiddle: https://jsfiddle.net/pbg44bqu/12/

like image 26
Scott Marcus Avatar answered Oct 05 '22 22:10

Scott Marcus