Generating element IDs with JavaScript and counters
The code that I posted in my previous post on creating a unique ID in JavaScript is fairly similar to code that’s all over the internet and seemed like it should work. And to be fair, it did work, although with one major problem. If the code runs too quickly it’s possible for two elements to have the same “unique” id.
What I came up with instead was using a counter to keep track of the last ID given and increment it each time.
JavaScript:
-
var uniqueCounter=0;
-
function generateUniqueID()
-
{
-
uniqueCounter++;
-
return uniqueCounter.toString(16);
-
}
I wanted to have the number returned as hex which is why the .toString(16) is on the end. No real reason, it just seemed like the right thing to do. If you just want a number you can use this.
JavaScript:
-
var uniqueCounter=0;
-
function generateUniqueID()
-
{
-
return uniqueCounter++;
-
}
Question, Comments...
Do you have more questions. Please either leave a comment below or join us in our new forum.

