Wednesday, March 4, 2015

AddEventListener Vs Bind/On

After a long time, I had to AddEventListener and native javascript to do file drag and drop. jQuery bind or on methods to adding evening listeners are giving files names dragged with the drag event. Might be future challenge.

Experimental code:
Ref 1: http://www.sitepoint.com/html5-file-drag-and-drop/
Ref 2: https://github.com/merty/simple-file-uploader

<html >
<head>
<title>AddEventListener Vs Bind/On</title>
<style>
#filedrag
{
  display: none;
  font-weight: bold;
  text-align: center;
  padding: 1em 0;
  margin: 1em 0;
  color: #555;
  border: 2px dashed #555;
  border-radius: 7px;
  cursor: default;
  height: 140px;
}

#messages
{
  padding: 0 10px;
  margin: 1em 0;
  border: 1px solid #999;
}

</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script>
function event_arrestor(evt) {
  console.log( "%s started", evt.type);
  evt.stopPropagation();
  evt.preventDefault();
}

function process_drop(evt) {
  event_arrestor(evt)
  var files = evt.dataTransfer.files;
  var count = files.length;
  console.log("Totally " + count + " files were dropped");
  console.log(files);
  
  for (var i = 0, f; file = files[i]; i++) {
    var msg = "<p>File information: <strong>" + file.name +
      "</strong> type: <strong>" + file.type +
      "</strong> size: <strong>" + file.size +
      "</strong> bytes</p>";
    console.log(msg);
    $('#messages').append(msg);
  }
}

$(document).ready(function() {
  var filedrag = document.getElementById('filedrag');
  filedrag.style.display = "block";
  filedrag.addEventListener('dragenter', event_arrestor, false);
  filedrag.addEventListener('dragover', event_arrestor, false);
  filedrag.addEventListener('dragexit', event_arrestor, false);
  filedrag.addEventListener('dragleave', event_arrestor, false);
  filedrag.addEventListener('drop', process_drop, false);
  
  //$('#filedrag').css({display: "block"});
  // $('#filedrag').bind('dragenter', event_arrestor, false);
  // $('#filedrag').bind('dragover', event_arrestor, false);
  // $('#filedrag').bind('dragexit', event_arrestor, false);
  // $('#filedrag').bind('dragleave', event_arrestor, false);
  // $('#filedrag').bind('drop', event_arrestor, false);
  
  // $('#filedrag').bind({
    // dragenter: event_arrestor,
    // dragover: event_arrestor,
    // dragexit: event_arrestor,
    // dragleave: event_arrestor,
    // drop: function(evt){
      // console.log("DROPPED");
      // process_drop(evt);
      // return false;
    // } 
  // });
  
  
});
</script>

</head>
<body>

<h1>AddEventListener Vs Bind/On</h1>
<div id="filedrag"> Drop files here</div>
<div id="messages">
  <p>Status Messages</p>
</div>

</body>

</html>

No comments:

Post a Comment