HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Data URI encoder

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
uridataencoder

Problem

Review this code for code quality.


Data URI encoder

#dropbox {
  padding: 18.5px 0;
  max-width: 499px;
  border: 2px dashed #bbb;
  border-radius: 5px;
  color: #bbb;
  text-align: center;
}

Data URI encoder
Select or drag a file to get the Data URI: 
Drop file here

var fileinput = document.getElementById("fileinput"),
  dropbox = document.getElementById("dropbox"),
  filename = document.getElementById("filename"),
  content = document.getElementById("content"),
  filesize = document.getElementById("filesize");

function encodeDataURI(e) {
  e.stopPropagation();
  e.preventDefault();

  var files = e.target.files || e.dataTransfer.files,
    file = files[0],
    reader = new FileReader();

  reader.onload = (function() {
    return function(e) {
      content.value = e.target.result;
      filename.textContent = file.name;
      filesize.innerHTML = "Data URI size: " + e.target.result.length + " bytes" + "Original size: " + file.size + " bytes"
    };
  })();

  reader.readAsDataURL(file);
}

function handleDragOver(e) {
  e.stopPropagation();
  e.preventDefault();
  e.dataTransfer.dropEffect = "copy";
}

dropbox.addEventListener("dragover", handleDragOver, false);
dropbox.addEventListener("drop", encodeDataURI, false);
fileinput.addEventListener("change", encodeDataURI, false);

Solution

There isn't much here, just a few comments though:

-
Most developers I come across use var per variable rather than comma separated. It's down to personal preference and code habits though, so you could ignore this one.

An advantage I see is that it makes variable declaration easier to move around without worrying about the connecting commas.

-
I don't see the benefit of using a closure for reader.onload. You can simply just assign it a function.

-
Further, you can move out the reader.onload handler function outside encodeDataURI. That way, the code won't generate that handler function for every call of encodeDataURI. Optimizing JS engines will do this for you though, but it's best practice if you just code it that way.

-
Programming languages were designed for people. Name your variables verbosely. For instance, e into event. Short variables are only good in the short-term. Long-term, they aren't good for maintenance. Don't worry about file sizes, that's what minifiers are for.

Context

StackExchange Code Review Q#38083, answer score: 3

Revisions (0)

No revisions yet.