-
Notifications
You must be signed in to change notification settings - Fork 2
/
image-loader.js
100 lines (79 loc) · 2.9 KB
/
image-loader.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
/*
* image-loader
* https://github.com/goschevski/image-loader
* Copyright (c) Aleksandar Gosevski
*/
;(function () {
var defaults = function (defaults, options) {
for (var key in options) {
if (options.hasOwnProperty(key)) {
defaults[key] = options[key];
}
}
return defaults;
};
var ImageLoader = function (element, options) {
if (!this.isSupported) {
throw new Error('Older browsers are not supported.');
}
var opts = typeof options !== 'undefined' ? options : {};
if (typeof opts !== 'object' || Array.isArray(opts)) {
throw new Error('Options must be passed as object!');
}
this.setElements(element, opts);
this.bindEvents();
};
ImageLoader.prototype = {
defaults: {
placeholder: '.image-placeholder',
width: 'auto',
height: 'auto',
imgClass: 'img-load',
method: 'html',
callback: null
},
isSupported: function () {
return window.File && window.FileReader && window.FileList && window.Blob;
},
setElements: function (element, options) {
this.options = defaults(this.defaults, options);
this.$element = document.querySelectorAll(element)[0];
this.$placeholder = document.querySelectorAll(this.options.placeholder)[0];
},
bindEvents: function () {
this.$element.addEventListener('change', this.render.bind(this), false);
},
render: function (e) {
var uploader = e.currentTarget,
reader = new FileReader(),
self = this,
o = this.options;
reader.onload = (function (file) {
return self[ o.method === 'css' ? 'setBackground' : 'setImage' ].bind(self);
}(uploader.files[0]));
reader.readAsDataURL(uploader.files[0]);
// If callback is function, execute it
if (typeof o.callback === 'function') {
o.callback();
}
},
setImage: function (e) {
var o = this.options;
var image = '<img src="' + e.target.result + '" width="' + o.width + '" height="' + o.height + '" class="' + o.imgClass + '">';
if (o.method === 'html') {
this.$placeholder.innerHTML = image;
return;
}
if (o.method === 'append') {
this.$placeholder.innerHTML = this.$placeholder.innerHTML + image;
return;
}
throw new Error('Only html and append methods are allowed!');
},
setBackground: function (e) {
this.$placeholder.style.backgroundImage = 'url(' + e.target.result + ')';
return;
}
};
window.ImageLoader = ImageLoader;
})();