user8575948
user8575948

Reputation: 23

Localstorage in my script seems not to be working

I have made some html/JavaScript codes like this:

<script>
if(window.localStorage!==undefined)
{
 }
else{ alert('Your browser is outdated!'); }
function myfunction1{
if(localStorage.getItem('permission')!="") { localStorage.setItem('permission', pressed);} 
function myfunction2{ document.getElementById('data').innerHTML = localStorage.getItem('permission');}
</script>
<body onload="myfunction2()">
<p id="data">this paragraph shows storage data</p>
<button onclick="myfunction1()">press</button>

The first script is for checking whether the browser supports localstorage. Second script (myfunction1) checks if there is any data called "permission". If there is none, then it will make one. Third code (myfunction2) is for showing the localstorage data. But none of these are working. Maybe there is a simple problem on my code. But I can't fix it. Please help.

Upvotes: 1

Views: 4350

Answers (1)

dvr
dvr

Reputation: 895

You have several syntax errors in your code:

  1. You can check wether you web browser supports localStorage or not, just by doing typeof(Storage) === "undefined", works for localStorage / sessionStorage.
  2. Your functions need the correct syntax i.e. function name() {handle}
  3. You didn't defined pressed, if a String is what you needed you forgot the double quotes"pressed" around it.

<script>
if(typeof(Storage) === "undefined") {
  alert('Your browser is outdated!'); 
}

function myfunction1() {
  if(localStorage.getItem('permission')!="") 
  { localStorage.setItem('permission', 'pressed');} 
}

function myfunction2()  { 
  document.getElementById('data').innerHTML = localStorage.getItem('permission');
}

</script>

<body onload="myfunction2()">
<p id="data">this paragraph shows storage data</p>
<button onclick="myfunction1()">press</button>
</body>

Upvotes: 1

Related Questions