-2

What do I need to insert in this script for the variable to be cached and after I refresh the page in the browser, the variable stays the same?

   <script>
   var WishCounter = 0;
   $(document).ready(function(){
          $(".accordion-heading").click(function(){
                if($(".accordion-body").is(':visible')){  /* check the condition accordion-body is visible or not */
                    $(".accordion-body").slideUp(200);  /*if content is visible then close accordion-body with specific time duration */
                  $(".plusminus").text('+')    /* add plus sign */
              }
              else{
                  $(this).next(".accordion-body").slideDown(200); /*if content not visible then
                                                                                                              show the accordion-body */
                  $(this).children(".plusminus").text('-');  /* add minus sign */
              }
          });
          $(".add-to-cart2").click(function(){
              WishCounter++;
              localStorage.setItem('WishCounter', WishCounter);
              $(".cart-wish").text(WishCounter);
              localStorage.getItem('WishCounter')



          });
      });

      </script>
  • 1
    Possible duplicate of [Persist variables between page loads](https://stackoverflow.com/questions/29986657/persist-variables-between-page-loads) –  Aug 23 '19 at 16:02

3 Answers3

0

There are many ways to do this, but the simplest way with the least setup required is Local Storage. It works as a Map, and persists upon browser refresh.

Enioluwa Segun
  • 911
  • 8
  • 12
0

I would use window.localStorage for this. It allows you to store data in the browser and it will persist even after closing the window.

Every time you modify WishCounter call localStorage.setItem('WishCounter', WishCounter);

When you start the website just call localStorage.getItem('WishCounter'); to get the data.

EDIT: I forgot to mention that you need to define localStorage as window.localStorage (let localStorage = window.localStorage)

KolCrooks
  • 514
  • 1
  • 5
  • 12
  • I rewrote the code above, I put it in the website but unfortunately it does not work, probably something I do not do well. Can you please tell me exactly how to insert the lines of code provided by you? – Alexandru Cristian Aug 23 '19 at 16:13
  • You are setting wishcounter back to 0 right before you get it every time – KolCrooks Aug 24 '19 at 23:02
0

Localstorage is used for data with no expiration date, however sessionstorage is only stored for one session. To set a value to localstorage, one needs to use localStorage.setItem(key,value);. To get the value from localstorage, one needs to use localStorage.getItem(key);. However for both setItem and getItem, the value and key must be strings.

ds_secret
  • 338
  • 3
  • 18