Skip to content

Instantly share code, notes, and snippets.

@bishopZ
Created February 3, 2013 18:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bishopZ/4702885 to your computer and use it in GitHub Desktop.
Save bishopZ/4702885 to your computer and use it in GitHub Desktop.
LocalStorage Example
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Cat Walk</title>
</head>
<body>
<img style="position:absolute;" src="cat.gif">
<script>
var img = document.getElementsByTagName('img')[0];
var lastLeft = localStorage.getItem('walkLoc');
img.style.left = (!isNaN(lastLeft)) ? lastLeft + 'px' : '0px';
var walkForwards = JSON.parse(localStorage.getItem('walkForwards'));
function setWalk(v){
walkForwards = v;
setTimeout(function(){
localStorage.setItem('walkForwards', v);
},1);
}
function setLoc(currentLeft){
img.style.left = (currentLeft) + 'px';
setTimeout(function(){
localStorage.setItem('walkLoc', currentLeft);
},1);
}
function catWalk() {
var currentLeft = parseInt(img.style.left);
if (walkForwards && (currentLeft > (window.innerWidth-img.width))) {
setWalk(false);
}
if (!walkForwards && (currentLeft <= 0)) {
setWalk(true);
}
if (walkForwards) {
setLoc(currentLeft + 10);
} else {
setLoc(currentLeft - 10);
}
}
window.setInterval(catWalk, 50);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment