Styling Native File Input

by Faisal Khan Janjua

HTML

<h2>Styling Native File Input</h2>

<div class="file-drop-area">
  <span class="fake-btn">Choose files</span>
  <span class="file-msg">Drag and Drop File Here</span>
  <input class="file-input" type="file" multiple>
</div>

SCSS

body {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-between;
  background: linear-gradient(to right, #4568dc, #b06ab3);
  color: #D7D7EF;
  font-family: 'Lato', sans-serif;
}

h2 {
  margin: 50px 0;
}

section {
  flex-grow: 1;
}

.file-drop-area {
  position: relative;
  display: table;
  align-items: center;
  width: 450px;
  max-width: 100%;
  padding: 25px;
  border: 1px dashed rgba(255, 255, 255, 0.4);
  border-radius: 3px;
  transition: 0.2s;
  overflow: hidden;
  &.is-active {
    background-color: rgba(255, 255, 255, 0.05);
  }
}

.fake-btn {
  background-color: rgba(255, 255, 255, 0.04);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 3px;
  padding: 8px 15px;
  margin-right: 10px;
  font-size: 12px;
      cursor: pointer;
  text-transform: uppercase;
}

.file-msg {
  font-size: small;
  font-weight: 300;
  line-height: 1.4;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.file-input {
  position: absolute;
  left: 0;
  top: -22px;
  height: 150%;
  width: 100%;
  cursor: pointer;
  opacity: 0;
  &:focus {
    outline: none;
  }
}

footer {
  margin-top: 50px;
  a {
    color: rgba(255, 255, 255, 0.4);
    font-weight: 300;
    font-size: 14px;
    text-decoration: none;
    &:hover {
      color: white;
    }
  }
}

JavaScript

var $fileInput = $('.file-input');
var $droparea = $('.file-drop-area');

// highlight drag area
$fileInput.on('dragenter focus click', function() {
  $droparea.addClass('is-active');
});

// back to normal state
$fileInput.on('dragleave blur drop', function() {
  $droparea.removeClass('is-active');
});

// change inner text
$fileInput.on('change', function() {
  var filesCount = $(this)[0].files.length;
  var $textContainer = $(this).prev();

  if (filesCount === 1) {
    // if single file is selected, show file name
    var fileName = $(this).val().split('\\').pop();
    $textContainer.text(fileName);
  } else {
    // otherwise show number of files
    $textContainer.text(filesCount + ' files selected');
  }
});