Skip to content Skip to sidebar Skip to footer

Unique Random Div Id Using Javascript

I need a javascript which make Unique Random DIV ID. Currently i am using it with PHP

Solution 1:

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

functionmakeRandomStr(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);
});
<buttonid="run">Make Random</button><br><br><preid="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.

functionmakeRandomStr(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);
});
<buttonid="run">Make Random</button><br><br><preid="results"></pre>

Post a Comment for "Unique Random Div Id Using Javascript"