Created
May 12, 2015 02:59
-
-
Save Auraelius/9b9d282756881eca2618 to your computer and use it in GitHub Desktop.
local storage glossary
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> | |
<head> | |
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script> | |
<style> | |
body { | |
font-family: "Open Sans", sans-serif; | |
} | |
textarea { | |
height: 5em; | |
width: 40em; | |
} | |
#addButton { | |
background-color: lightgreen; | |
} | |
</style> | |
</head> | |
<body> | |
<h1>Glossary</h1> | |
<form id="theForm" action="#"> | |
<legend for="word">New Word</legend> | |
<input type="text" id="word" /> | |
<legend for="definition">Definition</legend> | |
<textarea name="definition" id="definition" ></textarea> | |
<br> | |
<button id="addButton">Add word to dictionary</button> | |
</form> | |
<h2>Word List</h2> | |
<dl id="wordList"></dl> | |
<script> | |
$(document).ready( function(){ | |
displayDictionary(getDictionary()); | |
$("#addButton").click(addWord); | |
}); | |
function addWord(e) { | |
var entry = {}; | |
entry.word = $("#word").val(); | |
entry.definition = $("#definition").val(); | |
var dictionary = getDictionary(); | |
dictionary.push(entry); | |
saveDictionary(dictionary); | |
displayDictionary(getDictionary()); | |
e.preventDefault(); | |
} | |
function displayDictionary(d){ | |
$wordList = $('#wordList'); | |
$wordList.html(" "); | |
$.each(d, function(index, entry){ | |
$wordList.append("<dt>" + entry.word + "</dt><dd>" + entry.definition + "</dd>"); | |
}); | |
} | |
function saveDictionary(d) { | |
localStorage.setItem('theDictionary', JSON.stringify(d)); | |
} | |
function getDictionary(){ | |
if (localStorage.getItem('theDictionary') === null){ | |
return(initDictionary()); | |
} else { | |
return(JSON.parse(localStorage.getItem('theDictionary'))); | |
} | |
} | |
function initDictionary(){ | |
var defaultDictionary = [ | |
{word: "foo", definition: "See 'bar'"}, | |
{word: "bar", definition: "See 'foo'"} | |
]; | |
return(defaultDictionary); | |
} | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment