Doubt with Localstorage -

Asked

Viewed 61 times

1

I have this code that is counting the amount of Clicks, only I wish that when closing the Browser the counter does not reset.

  var p = document.createElement("p");
  document.body.appendChild(p);

  $(document).ready(function(){
      var cout = 0;   
      $("#btnCount").click(function(){
          cout = cout+1;
          $('p').html(cout);
      });
  });    
    <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>Document</title>
        <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js"></script>
    </head>
    <body>
        <button type="button" id="btnCount">Click me</button>
    </body>
    </html>

3 answers

4

To save before closing the page

window.onbeforeunload = function(count) {
    localStorage.setItem('count', count);
}

How to recover from localstorage

var count = localStorage.getItem('count'); 

2

It is not necessary to store the localStorage when you exit the page or browser. Just create/update it within the event where clicks are counted, and the variable cout must have an operator || to have one of two values: 0 or that of localStorage if he exists.

Another thing, you can create the <p> with jQuery himself, as I suggest below:

$("body").append("</p>");
$(document).ready(function(){
   var cout = localStorage.getItem("cout") || 0;

   $("#btnCount").click(function(){
       cout = parseInt(cout)+1;
       $('p').html(cout);
       localStorage.setItem("cout", cout);
   });
});    

Another thing is that you need to convert the value of cout for int with parseInt() because localStorage is in string format.

0

You can use the function setItem from localStorage to store its counter variable, it has the following syntax

localStorage.setItem(keyName, keyValue);

You can add the following to your code to save to localStorage when the browser is closed.

Example

window.onbeforeunload = function(count) {
   localStorage.setItem('count', count);
}

Retrieve data

To recover the data we also own the run getItem

var count = JSON.parse(localStorage.getItem('count'));

Browser other questions tagged

You are not signed in. Login or sign up in order to post.