Created
June 5, 2021 12:32
-
-
Save arisetyo/a43f99a45df2f68ac614f6213aa3666f to your computer and use it in GitHub Desktop.
A simple example of using local storage
This file contains hidden or 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
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<meta http-equiv="X-UA-Compatible" content="ie=edge"> | |
<title>Local storage</title> | |
<style> | |
body { | |
font-family: Arial, Helvetica, sans-serif; | |
} | |
#root { | |
margin: 6px 0 12px 0; | |
} | |
button { | |
text-transform: uppercase; | |
} | |
</style> | |
</head> | |
<body> | |
<h1>HTML web storage; better than cookies.</h1> | |
<div id="root"></div> | |
<button onclick="storeToStorage()">store value to storage</button> | |
<button onclick="removeFromStorage()">remove value in storage</button> | |
<script type="text/javascript"> | |
var refreshScreen = () => { | |
if (typeof(Storage) !== 'undefined') { | |
var message = '<strong>Local storage value:</strong> '; | |
var locallyStoredVariable = localStorage.getItem("myLocalVariable"); | |
if (locallyStoredVariable) { | |
message = message + locallyStoredVariable; | |
} else { | |
message = message + 'not-yet-available'; | |
} | |
document.getElementById("root").innerHTML = message; | |
} else { | |
alert('No Web Storage support'); | |
return; | |
} | |
} | |
var storeToStorage = () => { | |
var value = 'Stuart takes care of the house. Raj cooks for the guys.'; | |
localStorage.setItem("myLocalVariable", value); | |
refreshScreen(); | |
} | |
var removeFromStorage = () => { | |
localStorage.removeItem("myLocalVariable"); | |
refreshScreen(); | |
} | |
refreshScreen(); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment