Last active
November 4, 2015 07:40
-
-
Save aratak/fb8c4bd92ca9b8a58843 to your computer and use it in GitHub Desktop.
Catch event when file is dropped or uploaded via button
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
%div{ style: 'display: none;' } | |
%input{ type: 'file', id: 'uploadImageInput' } |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#= 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