How do I develop a working example using this plugin: HTML5 JavaScript Pasting Image Data in Chrome
The author has put together a great example that seems like it would suit our purposes. I’m not familiar with creating a jQuery plugin however.
The goal will be to use this plugin to paste clipboard images into a rich text editor such as TinyMCE.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>PASTE IMAGE</title>
<script type="text/javascript" src="js/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.8.18.custom.min.js"></script>
<script type="text/javascript">
// Created by STRd6
// MIT License
// jquery.paste_image_reader.js
(function($) {
var defaults;
$.event.fix = (function(originalFix) {
return function(event) {
event = originalFix.apply(this, arguments);
if (event.type.indexOf('copy') === 0 || event.type.indexOf('paste') === 0) {
event.clipboardData = event.originalEvent.clipboardData;
}
return event;
};
})($.event.fix);
defaults = {
callback: $.noop,
matchType: /image.*/
};
$.fn.pasteImageReader = function(options) {
if (typeof options === "function") {
options = {
callback: options
};
}
options = $.extend({}, defaults, options);
return this.each(function() {
var $this, element;
element = this;
$this = $(this);
$this.bind('paste', function(event) {
var clipboardData, found;
found = false;
clipboardData = event.clipboardData;
Array.prototype.forEach.call(clipboardData.types, function(type, i) {
var file, reader;
if (found) {
return;
}
if (!type.match(options.matchType)) {
return;
}
file = clipboardData.items[i].getAsFile();
reader = new FileReader();
reader.onload = function(evt) {
options.callback.call(element, {
filename: file.name,
dataURL: evt.target.result
});
};
reader.readAsDataURL(file);
found = true;
});
});
});
};
})(jQuery);
$("html").pasteImageReader (results) ->
{filename, dataURL} = results
$("body").css
backgroundImage: "url(#{dataURL})"
</script>
</head>
<body>
</body>
</html>
I’m confused by the plugin call:
$("html").pasteImageReader (results) ->
{filename, dataURL} = results
$("body").css
backgroundImage: "url(#{dataURL})"
That doesn’t look like jQuery that I’ve seen. Is it specific to the plugin itself? Any guidance would be greatly appreciated!
Those last calls are in CoffeeScript, a language that compiles into JavaScript. (http://coffeescript.org)
Im no expert – in fact i’ve never used coffeescript at all – but It would compile to:
That would probably work, but I dont like how its formatted. Here’s some cleaner code.
Give that a shot, and see if you can make it work for you!