Drag and drop files to a textarea

This is not really a big thing, but it might be useful to some. And it is a good example of a more general approach.

Basically I wanted a textarea where the user could type text, like a normal textarea, but I also wanted the user to be able to drag and drop a file on the textarea and then the text from the file would appear in the area.

There are several very good and instructive drag and drop approaches in the forum (thank you!), but I did not want to create or use a custom component. I just wanted to add this feature to a regular textarea that existed on my page. Also, anvil has evolved, which has opened up new possibilities.

In short:

  • After the form with the textarea has loaded I get the textarea component (using get_dom_node)
  • Next: Call a javascript function with the component as an argument (use call_js). The javascript function adds event listeners to the textarea component (drag/drop).

This is all. When a file is dropped, the listener detects the event, reads the text from the file, and puts it into the textarea.

There are probably exceptions, corner cases and bugs (different browsers, what if it is not a textfile?), but the general approach works and is relatively short and clean.

Here is a link to demo:


And the code is here (Note the important js code in the Native Libraries):