PeeHaa
PeeHaa

Reputation: 72652

write a jquery function which accepts params and object

This should be an easy one.

How to write a jquery function that gets the 'calling' object and some params.

My function code:

new function($) {
  $.fn.addcolor = function(param1, param2, param3, param4) {
    // here i would like to retrieve the 'caller' object (div.foo in this case)

  }
} (jQuery);

My code that 'calls' the function:

$('div.foo').click(function() {
  $(this).addcolor(1, 2, 3, 4);
});

I can get the params no problemo, but I want to get the content of the div.foo in the function and add some content it.

Upvotes: 0

Views: 192

Answers (5)

Pawel Zubrycki
Pawel Zubrycki

Reputation: 2713

To extend jQuery I used:

(function($) {
    $.fn.extend({
        addcolor: function(param1, param2, param3, param4) {
            return this.empty().append(something);
        }
    });
})(jQuery);

Upvotes: 0

phillip
phillip

Reputation: 2738

this.whatever is one way...

There is also an arguments object that you can call. ie: arguments.length or arguments["parm"]

Upvotes: 1

Daff
Daff

Reputation: 44205

In jQuery plugin functions that element is referenced by this.

function($) {
  $.fn.addcolor = function(param1, param2, param3, param4) {
    // here i would like to retrieve the 'caller' object (div.foo in this case)
    var divcontent = $(this).html();
  }
} (jQuery);

Upvotes: 2

user113716
user113716

Reputation: 322452

In your addcolor plugin, this will represent the same jQuery object against which your plugin was called.

 // v---jQuery object
$(this).addcolor(1, 2, 3, 4);

(function($) {
  $.fn.addcolor = function(param1, param2, param3, param4) {
    // here "this" is the same object
    // this[ 0 ] to get the first DOM element
    // this.each(function(...   to iterate over the collection
  }
})(jQuery);

Upvotes: 2

SLaks
SLaks

Reputation: 887275

You're looking for this.

jQuery plugins in $.fn are normal methods on the $ prototype. (jQuery assigns $.fn to $.prototype)
Like any other method, you can get the context in which it was invoked using this.

Upvotes: 2

Related Questions