JSFiddle - React, Tailwind, and code Playground

by micsel

HTML

<p>Clicking the link below should prompt with "Leave" or "Cancel" option. If you check the box, then click on the link, and then click on "Cancel", the checkbox should return to false.</p>

<div>
  <a href="https://www.google.com">Click here to exit this site and go to google.com</a>
</div>

<div class="checkbox">
  <input type="checkbox" id="checkbox">
</div>

CSS

.checkbox {
  margin-top: 20px;
  margin-left: 20px;
}

JavaScript

window.onload = () => {

  // declaration & Initialization
  const input = document.createElement("input");
  const defaultCounterValue = 10; // incremental --
  const defaultIntervalValue = 50; // ms
  const checkbox = document.getElementById('checkbox');
  const setLocalStorage = (itemName, itemValue) => {
    localStorage.setItem(itemName, itemValue);
  };
  const getLocalStorage = (itemName) => {
    return localStorage.getItem(itemName) === null ? false : localStorage.getItem(itemName) === 'false' ? false : true;
  };

  let interval = undefined;
  let counter = defaultCounterValue;

  setLocalStorage('checkbox', getLocalStorage('checkbox').toString());

  setTimeout(() => {
    checkbox.checked = getLocalStorage('checkbox');
  }, 0);

  checkbox.addEventListener('click', () => {
    setLocalStorage('checkbox', checkbox.checked);
  });

  // set input property and event handlers
  input.type = 'checkbox';
  input.checked = false;
  input.style.display = 'none';
  input.addEventListener('click', () => {
    let removeInterval = () => {
      clearInterval(interval);
      interval = undefined;
    }

    if (interval) {
      removeInterval();
    }

    interval = setInterval(() => {
      if (input.checked === true) {
        if (counter === 0) {
          checkbox.checked = false;
          setLocalStorage('checkbox', checkbox.checked);
          counter = defaultCounterValue;
          input.checked = false;
        }
        counter--;
      } else {
        removeInterval();
      }
    }, defaultIntervalValue);
  });
  document.body.appendChild(input);

  // Event that run before the user leaves
  window.onbeforeunload = (event) => {
    event.preventDefault = true;
    event.cancelBubble = true;
    event.returnValue = null;
    input.checked = false;
    input.click();
  };
}