[Solved] Unique Random DIV ID using javascript [closed]


Here’s a simple random string generator in a working snippet so you can see what it generates:

function makeRandomStr(len) {
  var chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  var result = "", rand;
  for (var i = 0; i < len; i++) {
    rand = Math.floor(Math.random() * chars.length);
    result += chars.charAt(rand);
  }
  return result;
}

document.getElementById("run").addEventListener("click", function() {
  var div = document.createElement("div");
  div.innerHTML = makeRandomStr(40);
  document.getElementById("results").appendChild(div);
});
<button id="run">Make Random</button><br><br>
<pre id="results"></pre>

The ONLY way to guarantee perfectly unique in the world would be to have a central server that was keeping track of all previously allocated strings so no duplicate could ever be used. But since you did not specify how unique it needed to be, I offered a random string. If you make it longer, your odds of conflict go to near zero.


You can also add other environmental elements such as timestamp, mouse positions, etc… that make it even less likely to ever conflict.

For example, here a timestamp is added to the end of the string so you’d not only have to accidentally generate the same random string, but you’d also have to do it at exactly the same clock time.

function makeRandomStr(len) {
  var chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  var result = "", rand;
  for (var i = 0; i < len; i++) {
    rand = Math.floor(Math.random() * chars.length);
    result += chars.charAt(rand);
  }
  return result + "_" + Date.now();
}

document.getElementById("run").addEventListener("click", function() {
  var div = document.createElement("div");
  div.innerHTML = makeRandomStr(40);
  document.getElementById("results").appendChild(div);
});
<button id="run">Make Random</button><br><br>
<pre id="results"></pre>

5

solved Unique Random DIV ID using javascript [closed]