suraj
suraj

Reputation: 41

Adding a function to a dom element using jquery

I am trying to add a custom function to a specific div elements in my dom that share the same class name.

Something like this

$(".custom-div").each(function(){
        $(this).newFtn = function() {
            $(this).addClass("makeover");
        }
});

So here am trying to add the newFtn to the div elements with the class name ".custom-div".

After trial and error and inspecting of the element in firebug. I got this to work the following way

$(".custom-div").each(function(){
        $(this).init.prototype.newFtn = function() {
            $(this).addClass("makeover");
        }
});

But, I have a few question on this; I am not sure of why this works and are there any draw backs of doing it in this manner? Can someone explain this please ? An abstract explanation should be fine.

Upvotes: 2

Views: 4977

Answers (2)

pete
pete

Reputation: 25091

Try something like:

function DisableCheckBox(o) {
    //No need for $('selector') here as 'o' is a jQuery object already.
    o.each(function () {
        o.addClass('makeover');
    //Other stuff...
    });
    //optionally return o on function exit if you want to do stuff to it outside this function
}

DisableCheckBox($(".custom-div"));
//or
var chk = DisableCheckBox($(".custom-div")); //if returning 'o' above.

Upvotes: 1

James Allardice
James Allardice

Reputation: 166021

I think what you want to do is write a jQuery plugin. The basic idea is this:

(function($) {
    $.fn.newFtn = function() {
        this.each(function() {
            //Do stuff for each element in matched set
        });
    };
})(jQuery);

You can then apply this method to any jQuery object:

$(".custom-div").newFtn();

Note that this is the way most of the built-in jQuery methods work (they iterate over the matched set of elements themselves, so there's often no need to use each).

You can learn far more about jQuery plugin development by starting with the official tutorial.

If you really want to simply add a class to all of the elements in the matched set, there is absolutely no need to do any of this. Simply call addClass on the jQuery object. It will apply to all elements contained within that object.

Upvotes: 9

Related Questions