Showing posts with label jquery. Show all posts
Showing posts with label jquery. Show all posts

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?