-
-
Save evansharp/77fda1c91ebdd81e5e9a4b7f15a57ce3 to your computer and use it in GitHub Desktop.
Very simple autosave functionality using local storage
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
var AutoSave = (function(){ | |
var timer = null; | |
function getEditor(){ | |
var elems = document.getElementsByTagName("textarea") | |
if (elems.length <= 0) | |
return null; | |
return elems[0]; | |
} | |
function save(){ | |
var editor = getEditor(); | |
if (editor) { | |
localStorage.setItem("AUTOSAVE_" + document.location, editor.value ) | |
} | |
} | |
function restore(){ | |
var saved = localStorage.getItem("AUTOSAVE_" + document.location) | |
var editor = getEditor(); | |
if (saved && editor){ | |
editor.value = saved; | |
} | |
} | |
return { | |
start: function(){ | |
var editor = getEditor(); | |
if (editor.value.length <= 0) | |
restore(); | |
if (timer != null){ | |
clearInterval(timer); | |
timer = null; | |
} | |
timer = setInterval(save, 5000); | |
}, | |
stop: function(){ | |
if (timer){ | |
clearInterval(timer); | |
timer = null; | |
} | |
} | |
} | |
}()) |
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
<html> | |
<body> | |
<textarea rows=24 cols=80></textarea> | |
<script type="text/javascript" src="autosave.js"></script> | |
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.1.min.js"></script> | |
<script type="text/javascript"> | |
$(document).ready(function(){ | |
AutoSave.start(); | |
}) | |
$(window).unload(function(){ | |
AutoSave.stop(); | |
}); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment