Avatar
Avatar

Reputation: 15186

How to get the type of the dragged item (file or text) when the dragover event fires?

I have a textarea that detects if an element (e. g. image file) is dragged over it.

// drag and drop for upload
$('body').on('dragover', 'textarea', function(e) 
{
    e.preventDefault();
    e.stopPropagation();
    
    // indicator for user
    $('.drophere').show();
});

The problem is that the indicator to drop shows also up when text is dragged over the textarea (and not a file).

I thought I could check the type of the dragged item.

The HTML_Drag_and_Drop_API says:

The drag data contains two pieces of information, the type (or format) of the data, and the data's value. The format is a type string (such as text/plain for text data), and the value is a string of text.

However, using console.log( e.originalEvent.dataTransfer ); in the code above does not reveal any data type.

The attribute types is always empty for text dragged but also for an image file dragged.

enter image description here

Where can I find the file type or plain/text type?

Upvotes: 1

Views: 1722

Answers (1)

Mahdi Akrami
Mahdi Akrami

Reputation: 643

you can't view type or items stored in dataTransfer object since when your drag is stopped javascript changes this object values and because objects are referenced in javascript you see the changed value after dropping the text. if you notice when you print data in the console they have values but when expanding objects they are empty.

enter image description here

so you can check the format in runtime but for debugging you can use other methods to store this object like clone object without reference. like that :

var types = $.extend(true, {}, e.originalEvent.dataTransfer.types)    
var item = $.extend(true, {}, e.originalEvent.dataTransfer.items[0])

console.log(types)
console.log(item)

enter image description here

Upvotes: 3

Related Questions