Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add new methods to the jQuery object?

Is there some way to add methods to jQuery's objects?

For example, I have jQuery object

a = $('div')

I'd like that every object which was assigned like that, would have particular method (doSomething()) so I could invoke it like

a = $('.foo')
a.doSomething()

b = $('.bar')
b.doSomething()
like image 237
evfwcqcg Avatar asked Jun 05 '12 09:06

evfwcqcg


1 Answers

You have to add your function to the $.fn namespace. Please note that inside the function, this will refer to the jQuery object, not a DOM object.

$.fn.doSomething = function () {
    this.css('color', 'red');
};

$('#retk').doSomething();

​ jsFiddle Demo

Please read about writing jQuery plugins for additional guidelines.

like image 57
kapa Avatar answered Oct 13 '22 23:10

kapa