Created
February 2, 2013 04:11
-
-
Save mdipierro/4696084 to your computer and use it in GitHub Desktop.
HTML5 JS that allows saving and loading client side of any textarea. The example assume jQuery but fileio.js does not need jQuery.
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
/* example: | |
<script src='fileio.js'> | |
<script>FileIO.check_browser()</script> | |
<textarea id="code"> | |
hello world | |
</textarea> | |
<a href="#" id="load-button">Load</a> | |
<a href="#" id="save-button" onclick="FileIO.save(jQuery('#code').val())">Save</a> | |
<script>FileIO.load('load-button',function(f){jQuery('#code').val(f.result)})</script> | |
*/ | |
var FileIO = { | |
check_browser: function(callback) { | |
if(!(window.File && window.FileReader && window.FileList && window.Blob)) { | |
callback || alert('Sorry, your browser is not supported. Try Chrome!'); | |
} | |
}, | |
save: function(data, name) { | |
if(!name) name = prompt('Save As'); | |
if(!name) return; | |
var data = 'data:application/octet-stream;base64,' + btoa( data ); | |
var node = document.createElement('a'); | |
node.download = name || self.location.pathname.slice(self.location.pathname.lastIndexOf('/')+1); | |
node.href = data || self.location.href; | |
var ev = document.createEvent("MouseEvents"); | |
ev.initMouseEvent("click", true, false, self, 0, 0, 0, 0, 0, false, false, false, false, 0, null); | |
return node.dispatchEvent(ev); | |
}, | |
load: function(id, loader) { | |
var handleFileSelect = function(evt) { | |
var files = evt.target.files; | |
// Loop through the FileList and render image files as thumbnails. | |
for (var i = 0, f; f = files[i]; i++) { | |
var reader = new FileReader(); | |
reader.onload = function(e) { loader(e.target); } | |
reader.readAsBinaryString(f); | |
} | |
} | |
document.getElementById(id).addEventListener('change', handleFileSelect, false); | |
} | |
}; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment