4

So, I am using jqPlot which has this stupid requirement that it needs an element's id attribute to plot.

However, my javascript uses jQuery, which operates on elements, and I don't want to rely on a div having an id.

Can I somehow, given a jQuery $(this) element, generate an id on the fly for a div and pass that id to my jqPlot function?

Something like this:

(function($){  //jquery plugin style
  $.fn.myPlot = function(){
       //Somehow get id for "this"
       var generatedId = somehowCreateID(this);
       jqPlot.plot( generatedId );
  }
})(jQuery);

Any tips appreciated!

Andriy Drozdyuk
  • 58,435
  • 50
  • 171
  • 272

3 Answers3

4

Since IDs must be guarenteed to be unqiue, but do not need to be random, it's much better to just use a monotonically increasing ID number with an alpha prefix like this:

function assignID(elem, prefix) {
   prefix = prefix || "autoId_";
   if (elem.id) {
      return (elem.id);
   } else {
       if (!assignID.cntr) {
           assignID.cntr = 1;
       }
       var id = prefix + assignID.cntr++;
       elem.id = id;
       return(id);
   }   
}

This uses a property of the function assignID.cntr to keep track of a counter that increments one each time it's used so the IDs assigned here will never be the same as a previously assigned ID.

You can then make sure any element always has an id by just doing this:

assignID(elem, "plot");

If you want a jQuery method that would do this, then you could do it like this:

jQuery.assignIDCntr = 1;
jQuery.fn.assignID = function(prefix) {
    prefix = prefix || "autoId_";
    return this.each(function() {
        if (!this.id) {
            this.id = prefix + jQuery.assignIDCntr++;
        }   
    });
}

And, then you would use it like this:

$(".myobjects").assignID("plot");
jfriend00
  • 683,504
  • 96
  • 985
  • 979
0
function generateID(element) {
    var id;
    do {
        id = "_" + Math.floor(Math.random() * 1000000000);
    } while (document.getElementById(id) != null);

    element.id = id;
    return id;
}
Yogu
  • 9,165
  • 5
  • 37
  • 58
0

You can use a counter prefixed with at least one letter (to be compliant with non-HTML5 documents):

(function($) {
    var counter = 0;
    $.fn.myPlot = function() {
       return this.each(function() {
           jqPlot.plot(this.id || (this.id = "plot" + counter++));
       });
    }
})(jQuery);
Frédéric Hamidi
  • 258,201
  • 41
  • 486
  • 479