forked from CSS-Tricks/DragAvatar
-
Notifications
You must be signed in to change notification settings - Fork 0
/
avatar.js
115 lines (84 loc) · 2.31 KB
/
avatar.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
// Required for drag and drop file access
jQuery.event.props.push('dataTransfer');
// IIFE to prevent globals
(function() {
var s;
var Avatar = {
settings: {
bod: $("body"),
img: $("#profile-avatar"),
fileInput: $("#uploader")
},
init: function() {
s = Avatar.settings;
Avatar.bindUIActions();
},
bindUIActions: function() {
var timer;
s.bod.on("dragover", function(event) {
clearTimeout(timer);
if (event.currentTarget == s.bod[0]) {
Avatar.showDroppableArea();
}
// Required for drop to work
return false;
});
s.bod.on('dragleave', function(event) {
if (event.currentTarget == s.bod[0]) {
// Flicker protection
timer = setTimeout(function() {
Avatar.hideDroppableArea();
}, 200);
}
});
s.bod.on('drop', function(event) {
// Or else the browser will open the file
event.preventDefault();
Avatar.handleDrop(event.dataTransfer.files);
});
s.fileInput.on('change', function(event) {
Avatar.handleDrop(event.target.files);
});
},
showDroppableArea: function() {
s.bod.addClass("droppable");
},
hideDroppableArea: function() {
s.bod.removeClass("droppable");
},
handleDrop: function(files) {
Avatar.hideDroppableArea();
// Multiple files can be dropped. Lets only deal with the "first" one.
var file = files[0];
if (typeof file !== 'undefined' && file.type.match('image.*')) {
Avatar.resizeImage(file, 256, function(data) {
Avatar.placeImage(data);
});
} else {
alert("That file wasn't an image.");
}
},
resizeImage: function(file, size, callback) {
var fileTracker = new FileReader;
fileTracker.onload = function() {
Resample(
this.result,
size,
size,
callback
);
}
fileTracker.readAsDataURL(file);
fileTracker.onabort = function() {
alert("The upload was aborted.");
}
fileTracker.onerror = function() {
alert("An error occured while reading the file.");
}
},
placeImage: function(data) {
s.img.attr("src", data);
}
}
Avatar.init();
})();