Skip to content

Instantly share code, notes, and snippets.

@gcmurphy
Created September 6, 2012 05:43
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save gcmurphy/3651776 to your computer and use it in GitHub Desktop.
Save gcmurphy/3651776 to your computer and use it in GitHub Desktop.
Very simple autosave functionality using local storage
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;
}
}
}
}())
<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>
@Tamim912
Copy link

Tamim

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment