Add (read and write) property of jQuery object

I would like to add a property to the jQuery object and therefore attach it to the DOM without polluting the DOM. In casu, the property I would like to add is called "hue". (But do not think of this property as a color)

Of course, it is possible to use the jQuery 'data' function, and this works great. However, this makes my code less readable.

$("#a").data("hue","123");
$("#b").data( $("#a").data("hue")  );

I also managed to create a getter and setter function that is already significantly readable.

$("#a").setHue(123);
$("#b").setHue(  $("#a").getHue()   ); 

Ultimately, I would like to write jQuery / javascript code as such:

$("#a").hue(123);
$("#b").hue(  $("#a").hue()   ); 

However, it does not work, and, evaluating it in firebug, my browser crashes.

Here is the code I've created so far. GetHue () and setHue ('123') work, Hue () does not.

//extend the jQuery object with some extra properties for sake of readability
(function($)
{
    $.fn.setHue = function(hue_value)
    {
        this.hue=hue_value;
        return this;
    };

    $.fn.getHue = function()
    {
        return this.hue;
    };

    $.fn.hue = function(hue_value)
    {
        if ( typeof hue_value === 'undefined' ){
            return this.getHue();
        } else {
            this.setHue();
            return this;
        }
    };


})(jQuery);

Googling, API jQuery . , DOM. , google'd .

+3
1

? http://jsbin.com/doxa/1/edit

(function($){

  $.fn.hue = function (value) {
    if(value) {
      return this.each(function() {
        $(this).data('hue', value);
      });
    }
    return this.data('hue');
  };

})(jQuery);

$(function () {
  $('#a').hue('xxx');
  $('#b').text($('#a').hue());
});
+1

All Articles