Random key

by Adam Azad

HTML

<p>
  <button class="btn btn-primary btn-sm" id="generateKeyBtn">Generate</button> a new random key</p>
<span id="key"></span>

CSS

@import url(https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css);
body {
  padding: 10px;
}

JavaScript

/* 
 * Title: Random key 
 * @author Adam Azad <[email protected]>
 */

const
  keyBtn = document.getElementById('generateKeyBtn'),
  keySpan = document.getElementById('key');

// Retrieves the key from localStorage and shows it in the span
const showKey = () => {

  if ('localStorage' in window) {

    let key = localStorage.getItem('randomKey');

    if (key) keySpan.innerHTML = key;

  }

}

// Saves the key to localStorage
const saveKey = (k) => {

  if ('localStorage' in window) {

    localStorage.setItem('randomKey', k);

  }

}

// Generate a random key
// based on the current time and Math.random()
const generateKey = () => {

  let d = new Date(),
    r = Math.floor(Math.random() * d.getTime());

  saveKey(r);
  showKey();

}


keyBtn.addEventListener('click', generateKey);

// Show the initial key if it exists
showKey();