Skip to content

Instantly share code, notes, and snippets.

@aratak
Last active November 4, 2015 07:40
Show Gist options
  • Save aratak/fb8c4bd92ca9b8a58843 to your computer and use it in GitHub Desktop.
Save aratak/fb8c4bd92ca9b8a58843 to your computer and use it in GitHub Desktop.
Catch event when file is dropped or uploaded via button
%div{ style: 'display: none;' }
%input{ type: 'file', id: 'uploadImageInput' }
#= require jquery
#= require underscore
#= require pubsub
$(document).on 'ready page:load ajaxComplete nested:fieldAdded', (e)->
$parent = $(e.field or e.target)
return if $parent.data('pubsubFile') is true
$parent.data('pubsubFile', true)
$parent.on 'dragenter', (e)=> pubsub.pub('onDragEnterFile', event: e); e.stopPropagation(); e.preventDefault(); return false;
$parent.on 'dragleave', (e)=> pubsub.pub('onDragLeaveFile', event: e); e.stopPropagation(); e.preventDefault(); return false;
$parent.on 'dragover', (e)=> pubsub.pub('onDragOverFile', event: e); e.stopPropagation(); e.preventDefault(); return false;
$parent.on 'drop', (e)=>
if _.any(e.originalEvent.dataTransfer.files)
file = _.first(e.originalEvent.dataTransfer.files)
return false unless file && file.type.match(/image.*/)
reader = new FileReader()
reader.onload = (e)-> pubsub.pub('onSendFile', dataUrl: e.target.result, file: file)
reader.readAsDataURL(file)
e.stopPropagation(); e.preventDefault();
return false
$parent.find('#uploadImageInput').each ->
pubsub.sub 'triggerUploadImageInput', => $(@).trigger('click')
$(@).on 'change', (e)->
file = _.first @files
return false unless file && file.type.match(/image.*/)
reader = new FileReader()
reader.onload = (e)=>
pubsub.pub 'onSendFile', dataUrl: e.target.result, file: file
$(@).val('')
reader.readAsDataURL(file)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment