Rayudu
Rayudu

Reputation: 1816

HTML5 Drag and Drop : display droppable elements in separate div (Java Script and Knockout JS)

I am beginner in Knockout and java script. I have a problem in my project. I am using HTML5 Drag and Drop API using Knockout javascript. Now I need to show all drop items in separate div. I have some code which is display the name of droppable Items. But I want display file not file name. Below is my sample demo.

I am okay with either knockout or pure java script. enter image description here

VIEW FIDDLE HERE

function ViewModel(){
    var self = this;
    this.dropZones = ko.observableArray([{
        'elements' : ko.observableArray([])  // just to see that the output is correct
    }]);

    this.dragover = function(e){
        console.log('dragOver');
        e.stopPropagation();
        e.preventDefault();
    }

    this.drop = function(e, data){
        console.log('drop');
        e.stopPropagation();
        e.preventDefault();
        var files = e.dataTransfer.files;
        for (var i = 0, f; f = files[i]; i++) {
            data.elements.push(f.name);
        }
        $('.drop_zone').css('background-color', '#ffffff');
    }

    this.dragenter = function(e, index){
        console.log('dragEnter');
        $('.drop_zone').eq(index).css('background-color', '#00ff00');
    }

    this.dragleave = function(e, index){
        console.log('end');
        $('.drop_zone').eq(index).css('background-color', '#ffffff');
    }
}

ko.applyBindings(new ViewModel());
.drop_zone {
    border: 2px dashed #bbb;
    -moz-border-radius: 5px;
    -webkit-border-radius: 5px;
    border-radius: 5px;
    padding: 25px;
    text-align: center;
    font: 20pt bold'Vollkorn';
    color: #bbb;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<div class="col-md-12" data-bind="foreach: dropZones">
    <div class="drop_zone" data-bind="event:{
                dragover:   function(data, e){ $root.dragover(e);},
                drop:       function(data, e){ $root.drop(e, $data);},
                dragenter:  function(data, e){ $root.dragenter(e, $index());},
                dragleave:  function(data, e){ $root.dragleave(e, $index());}
            }">Drop files here</div>
    <ul data-bind="foreach: elements" style="height: 100px">
        <li data-bind="text: $data"></li>
    </ul>
</div>

Upvotes: 0

Views: 493

Answers (1)

wahwahwah
wahwahwah

Reputation: 3177

Here's an example of how to get an image from a file and append it to a .preview element:

function readImage(file) {

    var reader = new FileReader();
    var image  = new Image();

    reader.readAsDataURL(file);  
    reader.onload = function(_file) {
        image.src    = _file.target.result;            
        image.onload = function() {
          $(".preview").append('<img src="' + this.src + '"/>' + '<p>' + this.name +'</p>');
        };     
    };

}

And a fiddle. HTH.

Upvotes: 2

Related Questions