Dima Deplov
Dima Deplov

Reputation: 3718

jQuery drag and drop image to textarea handle event

I want to make text area that will handle image drop event on it from the desktop.

I found that I could attach event to html element, but it doesn't work properly. I don't find any error, but it doesn't work. Here is my code:

var imageDragOver = function imageDragOver(evt)
{
    console.log('imageDragOver');
    evt.stopPropagation();
    evt.preventDefault();
}

var imageDrop = function imageDrop(evt)
{
    console.log('imageDrop');
    evt.stopPropagation();
    evt.preventDefault();

}


document.addEventListener($('textarea'), imageDragOver, false);
document.addEventListener($('textarea'), imageDrop, false);

There is no any message in console log. What I do wrong? I don't look for an already made solutions.

Upvotes: 2

Views: 6968

Answers (2)

Dima Deplov
Dima Deplov

Reputation: 3718

To handle drop event on your area (text area or div) you need to do this:

var dropzone = document.getElementById('ta'); // paste your dropzone id here
dropzone.ondrop = function(e){
    console.log('drop'); // for debugging reasons
    e.preventDefault();  // stop default behaviour

    readfiles(e.dataTransfer.files); // function to handle file(s) that was added to dropzone
};

Next you need to send this files to server and show it in the browser if you want.

function readfiles(files) {
var formData = new FormData(); // we initialise a new form that will be send to php 

for (var i = 0; i < files.length; i++) {  // if we have more that one file
    previewImg(files[i]); // function to preview images

formData.append('file'+i, files[i]);

}

formData.append('moreInfo','myValuableValue');// you can append additional string info

$.ajax({
    url: './path_to_file_handler.php',
    type: 'POST',
    data: formData,
    async: true,
    success: function (data) {
        console.log(data);
    },
    cache: false,
    contentType: false,
    processData: false
 });


}       


function previewImg(file) {
var reader = new FileReader();

reader.onload = function (event) {

     var image = new Image();

    image.src = event.target.result; // set image source

    image.width = 550; // a fake resize


    document.getElementById('body').appendChild(image); // append image to body

};
reader.readAsDataURL(file);
}

Code for testing path_to_file_handler.php

<?php 
  print_r($_POST);
  print_r($_FILES); 
?>

Hope it will help somebody.

Upvotes: 4

Mr. B.
Mr. B.

Reputation: 8717

A simple way with jQuery UI, check out:

EDIT:

Good luck! :-)

Upvotes: 2

Related Questions