localStorage
only holds strings. localStorage["vv"] = false;
stores the string "false"
, which is not falsy.
Normally I store JSON and parse it. That's probably overkill here, though, just store "Y"
or "N"
as the flag and check that:
var videoplayer = document.getElementById("videoplayerlayer");
var links = document.getElementsByTagName("a");
if (typeof localStorage !== 'undefined')
// ^^^^^^ Note 2
{
console.log("localStorage exists")
if(localStorage["vv"] == "N")
{
videoplayer.style.display = "none";
// No need, it's already stored - localStorage["vv"] = false;
}
else
{
for( var i=0; i<links.length; i++ )
// ^^^^---- Note 1
{
links[i].onclick = function()
{
localStorage["vv"] = "Y";
videoplayer.style.display = "block";
}
}
}
}
/* You don't want this, it'll throw an error, since we know `localStorage` is falsy
else
{
localStorage["vv"] == false;
}
*/
However, nothing in the logic reasonably sets localStorage["vv"]
to "N"
(the one assignment that was there was in a branch where it's already there). You'll need to add something to set it, unless you want to default to hiding the video player and only show it when localStorage["vv"]
is "Y"
(or if local storage isn't accessible).
For instance, this hides the player and only shows it if the flag is "Y"
on load or one of those links is clicked:
var videoplayer = document.getElementById("videoplayerlayer");
var links = document.getElementsByTagName("a");
if (typeof localStorage !== "undefined") {
if (localStorage.vv !== "Y") {
videoplayer.style.display = "none";
}
for (var i = 0; i < links.length; i++)
{
links[i].onclick = function()
{
localStorage["vv"] = "Y";
videoplayer.style.display = "block";
};
}
}
Note 1: Your code was falling prey to The Horror of Implicit Globals (that's a post on my anemic little blog). Be sure to declare your variables. See the "Note"
comment above.
Note 2: Your check for whether you can use local storage was incorrect. I've updated it to what you probably meant above, but see see here for more thorough checks you'll want to use.
Note 3: I would recommend using modern event handling rather than setting onclick
.