Given a large JSON table in localStorage and a given key, how to access an associated value, and use it as a condition to CSS ?
Given the following JSON:
var data = [
{ 'myKey': 'A', 'status': 0 },
{ 'myKey': 'B', 'status': 1 },
{ 'myKey': 'C', 'status': 1 },
{ 'myKey': 'D', 'status': 1 }
];
the following html to stylize:
<p id="A">AA</p>
<p id="B">BB</p>
<p id="C">CC</p>
<p id="D">DD</p>
and the following css :
.status1 { color: green; }
.status0 { color: red; }
It's one of the basic principle behind "click to favorite/ favorite list / favorite star".
Working example on fiddle, JQuery
0. Trick for Apps!: JSON & localStorage
/* To store JSON in localStorage, you compress it as string */
localStorage["results"] = JSON.stringify(data); // or lS.restults
/* Whenever you want to work on it, need to uncompress the JSON */
var data = JSON.parse(localStorage["results"]);
1. Create the meta functions: getJsonVal()
//META.Fn: pullVal
function getJsonVal(json, itemId) {
for (var i in json) {
if (json[i].myKey == itemId) {
return json[i];
}
}
}
2. Function checking the JSON value before to inject CSS class accordingly
//META.Fn: loadSwitch [check localStorage & set CSS
function loadSwitchCSS($set, i) {
setTimeout(function () {
var myID = $set.eq(i).attr('id'); // a. Get key [my case: from the html ID]
alert("look at:"+ myID);
var val = getJsonVal(data, myID).status;
// alert(data);
if (val == 1) { // c. CSS remove-add: so if...else... CSS
$set.eq(i).removeClass().addClass('status1');
} else {
$set.eq(i).removeClass().addClass('status0')
}
if (i < $set.length - 1) {
loadSwitchCSS($set, i + 1);
}
}, 100);
}
3. Fire the function on load:
loadSwitchCSS($('p'), 0);