Doubt with LocalStorage -

1

I have this code that is counting the amount of Clicks, but I wanted it when I close the Browser the counter does not clear.

  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><buttontype="button" id="btnCount">Click me</button>
    </body>
    </html>
    
asked by anonymous 08.11.2018 / 19:24

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'); 
    
08.11.2018 / 19:36
2

You do not need to store the localStorage when you leave the page or browser. Just create / update it within the event where the clicks are counted, and the cout variable must have a || operator to have one of two values: 0 or localStorage if it exists. >

Another thing, you can create <p> with jQuery itself, 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 from cout to int with    parseInt() because the localStorage is in string format.

    
08.11.2018 / 20:20
0

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

localStorage.setItem(keyName, keyValue);

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

Example

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

Retrieve the data

To recover the data we also have the function getItem

var count = JSON.parse(localStorage.getItem('count'));
    
08.11.2018 / 19:44