Local Storage and JSON

zombiejson.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>JavaScript Example</title>
  
  	<script type="text/javascript">
	// Zombie constructor
	function Zombie(name, deathDate, food) {
		this.name = name;
		this.deathDate = deathDate;
		this.food = food;
		
		this.intro = function() { 
			return "I am " + name + ". Like " + food + "!"; 
		}
	}
	
	
	var zombie = null;
	

	// If the global zombie variable is not null, save it in localStorage
	// by stringifying it.
	function saveZombie() {
		if (zombie != null)
			localStorage.setItem("zombie", JSON.stringify(zombie));
	}
	
	// Load the zombie from localStorage.  If there is not a zombie,
	// then prompt the user for one.
	function loadZombie() {
		zombie = JSON.parse(localStorage.getItem("zombie"));
		
		if (zombie == null) {
			// Request a Zombie
			var name = prompt("Give me a zombie name");
			var dd = prompt("Give me a zombie death date");
			var food = prompt("Give me a zombie food");
			zombie = new Zombie(name, dd, food);
		}
		
		// Write the zombie to the element in the page
		document.getElementById("zombieview").textContent = JSON.stringify(zombie);
	}	
	
	// Function to remove zombie from localStorage and
	// set the global variable to null
	function destroyZombie() {
		localStorage.clear();
		zombie = null;
	}
		
	</script>
</head>

<!-- when the page loads, try to load a zombie from localStorage
     with our loadZombie() function (event handler) -->
<!-- when the page unloads (user goes somewhere else), call
     the saveZombie() function to save our zombie to local storage -->
<body onunload="saveZombie()" onload="loadZombie()">
    <h1>JavaScript Example</h1>
	
	<p id="zombieview"></p>
	<button onclick="destroyZombie()">Destroy Zombie</button>
</body>
</html>