[JavaScript] Setting Implementation via JSON and Web Storage (localStorage)
Implement setting feature to save user preferences in web application via JSON, Web Storage (localStorage), and JavaScript.
Source Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | <!doctype html> <html> <head> <meta charset="utf-8"> <title>JavaScript implement setting via JSON and Web Storage (localStorage)</title> </head> <body> <input type="checkbox" checked="checked" id="en"/><span>English</span><br> <input type="checkbox" checked="checked" id="ja"/><span>Japanese</span><br> <br> <span>Order:</span> <select id="order"> <option value="eng" selected="selected">English First</option> <option value="jpa">Japanese First</option> </select> <script src="app.js"></script> </body> </html> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | "use strict"; function SaveSetting(s) { localStorage.mySetting = JSON.stringify(s); } function LoadSetting() { return JSON.parse(localStorage.mySetting); } function SetupSetting() { var enElm = document.getElementById("en"); var jaElm = document.getElementById("ja"); var orderElm = document.getElementById("order"); var setting = { en: true, ja: true, order: "eng", }; // check if there is saved setting in user browser if (typeof localStorage.mySetting === 'undefined') { setting.en = enElm.checked; setting.ja = jaElm.checked; setting.order = orderElm.options[orderElm.selectedIndex].value; } else { setting = LoadSetting(); enElm.checked = setting.en; jaElm.checked = setting.ja; orderElm.value = setting.order; } enElm.addEventListener("click", function(e) { setting.en = enElm.checked; SaveSetting(setting); }); jaElm.addEventListener("click", function(e) { setting.ja = jaElm.checked; SaveSetting(setting); }); orderElm.addEventListener("change", function(e) { setting.order = orderElm.options[orderElm.selectedIndex].value; SaveSetting(setting); }); } SetupSetting(); |
To implement setting feature via GopherJS, see [2].
Tested on:
- Chromium Version 55.0.2883.87 Built on Ubuntu , running on Ubuntu 16.10 (64-bit)
References:
[1] | pali/setting.go at master · siongui/pali · GitHub pali/json.go at master · siongui/pali · GitHub |
[2] | [GopherJS] Setting Implementation via JSON and Web Storage (localStorage) |