Sunday, October 12, 2008

Simple JQuery UID Plugin

UID's can be tricky to make, but here's a simple one for discussion.

I'm posting this to see if anyone can make it a little safer to prevent collisions and/or improve the algorithm. Any thoughts? The prefix allow you to create uids you can select with a prefix on. The random string will give you a fairly large but not unmanageable string. We'll also return the JQuery instance so we can continue our chain.


(function($){
$.fn.uid = function(prefix) {
if (!prefix) {
prefix = "uid";
}
var generate = function() {
var dt = new Date().getMilliseconds();
var num = Math.random();
var rnd = Math.round(num*100000);
return prefix+dt+rnd;
};
return this.each(function() {
this.id = generate();
return $;
});
};
})(jQuery);

Usage:
$().ready(function() {
$('div').uid().css('background-color','blue');
});


Oui? Non?

3 comments:

cwillu said...

[ajpiano] http://ihatecode.blogspot.com/2008/10/simple-jquery-uid-plugin.html
* teppi|work has quit (Read error: 113 (No route to host))
[cwillu_remote] ajpiano, he could just increment a counter instead of the whole 'date and random' thing
[cwillu_remote] they're gonna be regenerated on each page load anyway
[ajpiano] i think his idea is to come up with a number that no one on the entire internet has ever heard of
[cwillu_remote] ajpiano, he's reinventing uuid's, badly?
[ajpiano] post a comment
[cwillu_remote] done.

:p

Anonymous said...

I agree the previous coment, incrementing a variable would be easier.

Here you have an example code:

(function($){
var _next_uid = 0;
$.fn.uid = function(prefix) {
return this.each(function() {
this.id = (prefix || 'uid') + (_next_uid++);
return $;
});
};
})(jQuery);

As you can see the new extension is much more simple.

For testing you could try this:

$(document).ready (function () {
for (i = 0; i < 100; i++) {
$("<" + "div>new div<" + "/" + "div>").uid ().appendTo ('body');
}
});


Sorry for splitting the "div" tag, but I had trouble publishing html tags (it is not allowed).

Alan L said...

I agree with the date + random method though, since that function does not need to consider any variable scopes - what if you need to run the UID function in more than one scope? The incremental method would cause collisions.