Using dataTransfer and other HTML5 event properties with jQuery Events

Update: I put this utility up at datauri.com for convenience. Update: The jQuery.event.props event property list has since been documented in the Event Object documentation.

This past weekend, I made a handy utility for converting files to data URLs. This utility is part of a larger tool that we are developing for a client.

I used the dragenter dragover and drop native host events to respond to drag/dropping files from the desktop. The event objects supplied to the drag host events have a special dataTransfer property which holds information about the user interaction, including what files (if any) the user dropped on the element to which the event is bound.

If there are files on the dataTransfer, you can pass this FileList to a FileReader to using one of the FileReader methods like so:

This is the second project on which I’ve worked with the native host drag events, and since I was using jQuery for other parts of the code, I decided to use jQuery to bind to the drag events.

For performance reasons, jQuery copies the event object for every event, and only copies the minimum viable properties required for what it needs to do. Unfortunately dataTransfer is not on this list, because it was not available three years ago when this decision was made. jQuery selects the properties to copy for each event object based on the jQuery.event.props string which is split into an array on initialization.

So, in order to get a FileList out of a native host drag event object when binding with jQuery, you have to push the dataTransfer property onto the jQuery.event.props array:

After doing this, the jQuery copy of each event object will get a dataTransfer property. Since jQuery.event.props is not formally exposed, it should not be considered stable for use in production code. I imagine that eventually some API for adding properties to the jQuery event object will be exposed, or perhaps a new approach will be taken to expose access to emerging native and native host event properties in the jQuery event callback system. It is not clear that this approach will work with future versions of jQuery, so use with caution. There is currently an open ticket in the jQuery bug tracker dealing with this issue.

You can see a completed implementation below, or try out the data urlifier at http://static.bocoup.com/code/dataurl

This entry was posted by Boaz Sender (@boazsender) on December 20, 2010 in HTML5, JavaScript, jQuery and Open Web Apps.

Comments

Author

This entry was posted by Boaz Sender (@boazsender) on December 20, 2010 in HTML5, JavaScript, jQuery and Open Web Apps.

Recent posts from this author

Related on the Bocoup Blog

Advertisement

Twitter

Google+