Search code examples
javascripthtmlvariablespageviews

How do you make a variable that is changing every reload?


The variable I'm talking about is like page views. I want it so the variable doesn't start at 1 every time. So every time you reload it, the pageviews variable adds by 1. All I have is:

HTML:

<div id='pageviews'></div>

Javascript:

var pageviews;
pageviews += 1;
document.getElementById('pageviews').innerHTML = pageviews;

I didn't use CSS because that was optional.


Solution

  • Use localStorage to store the count as :

    var count = 0;

    localStorage.setItem('count', count);

    and use var count = localStorage.getItem('count'); to retrieve the value (remember localstorage stores as string and not as integer so you can't directly use it as an integer.

    OR

    Use Cookies, set a cookie by setcookie(), although you will have to set some Expiry date to it.

    EDIT : This is exactly what to want to achieve. Hope it helps.