Javascript Browser Window localStorage Property count clicks

Introduction

The following example counts the number of times a user has clicked a button:

Click the button to see the counter increase.

Close the browser tab, and try again, and the counter will continue to count.

View in separate window

<!DOCTYPE html>
<html>
<head>
<script>
function clickCounter() {// w  w w .  ja v  a2 s .  com
  if(typeof(Storage) !== "undefined") {
    if (localStorage.clickcount) {
      localStorage.clickcount = Number(localStorage.clickcount)+1;
    } else {
      localStorage.clickcount = 1;
    }
    document.getElementById("result").innerHTML = "You have clicked the button " + localStorage.clickcount + " time(s).";
  } else {
    document.getElementById("result").innerHTML = "Sorry, your browser does not support web storage...";
  }
}
</script>
</head>
<body>

<p><button onclick="clickCounter()" type="button">Click me!</button></p>
<div id="result"></div>
</body>
</html>



PreviousNext

Related