javascriptonclickclick-counting

Display click count in JavaScript before the count


I have a simple script designed to increment a counter each time an image is clicked:

<script>
function clickCounter() {
  if (typeof(Storage) !== "undefined") {
    if (localStorage.clickcount) {
      localStorage.clickcount = Number(localStorage.clickcount) + 1;
    } else {
      localStorage.clickcount = 1;
    }
    document.getElementById("counter").innerHTML = localStorage.clickcount;
  } else {
    document.getElementById("counter").innerHTML = "Your browser does not support web storage...";
  }
}
</script>

The html:

<img id="heart" src="../assets/images/redheart.png" title="Give Love!" onclick="clickCounter()"><p id="counter"></p>

It's working fine but I'd like to be able to display the count BEFORE the click. Right now the counter shows only once the image button is clicked.

Thanks for any and all input.


Solution

  • If this isn't what you're going for, please let me know.

    First, a few tweaks:

    Behavior:

    On first page load…

    enter image description here

    Then we perform five clicks followed by a page refresh.

    enter image description here

    Note: This demo will not work here on Stack Overflow due to security restrictions in the editor. Have a look over in the fiddle I've created.

    document.querySelector("button").addEventListener("click", clickCounter);
    document.addEventListener("DOMContentLoaded", showValue);
    
    let counter = document.getElementById("counter");
    
    function showValue() {
      counter.innerHTML = `Current count = ${localStorage.clickcount || 0}`;
    }
    
    function clickCounter() {
      if (typeof(Storage) !== "undefined") {
        if (localStorage.clickcount) {
          localStorage.clickcount = Number(localStorage.clickcount) + 1;
        } else {
          localStorage.clickcount = 1;
        }
        showValue();
      } else {
        counter.innerHTML = "Your browser does not support web storage...";
      }
    }
    button {
      background-image: url(http://icons.iconarchive.com/icons/benzlee/free-christmas/512/heart-icon.png);
      background-repeat: no-repeat;
      background-size: 64px 64px;
      background-color: transparent;
      border: none;
      display: inline-block;
      width: 64px;
      height: 64px;
      cursor: pointer;
    }
    <button title="Give Love!" aria-label="Give Love!">
    <div id="counter"></div>

    https://jsfiddle.net/mgejhcnf/3/