rockstardev
rockstardev

Reputation: 13527

Writing your own Jquery function?

I want to write a function so that I can execute commands like so:

$("#Button").glow();

What do I have to override, or how do I have to structure the "glow" function so that I can call it the way I do above?

Upvotes: 1

Views: 4648

Answers (6)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038810

Take a look at plugin authoring. Read documentation. Do and try something. Like for example:

(function($) {
    $.fn.glow = function(options) {  
        return this.each(function() {     
            // TODO: do something for each element that matched your selector
        });
    };
})(jQuery);

Upvotes: 9

Snake Eyes
Snake Eyes

Reputation: 16764

You must declare a jQuery function like as:

jQuery.fn.myPlugin = function() {

  // Do your awesome plugin stuff here

};

and after that

$("#Button").myPlugin();

read here http://docs.jquery.com/Plugins/Authoring

Upvotes: 9

Tys
Tys

Reputation: 3610

(function( $ ){

  $.fn.glow = function() {

    //your selected element is 'this'
    this. ...//do your magic

  };
})( jQuery );

And then you can use it like this:

$('#element').glow();

For complete info, check this: http://docs.jquery.com/Plugins/Authoring

Upvotes: 2

rockstardev
rockstardev

Reputation: 13527

jQuery.fn.glow = function () {
  //Do Stuff
}

Upvotes: 1

Rob W
Rob W

Reputation: 348992

(function($) {
    $.fn.glow = function() {
       return this.each(function() { //<--optionally, parameters here
           // your logic here
           // `this` at this point refers to the DOM element
       });
    }
})(jQuery); //<-- Closure to allow using $ where $ is not jQuery any more

return in return this.each(..) enables chaining jQuery plugins, so that you can use:

$("selector").glow().anothermethod();
//If return was omitted, the previous line would throw an error

Upvotes: 7

Patrick Evans
Patrick Evans

Reputation: 42736

http://docs.jquery.com/Plugins/Authoring

all you need to know about making you're own plugin.

Upvotes: 3

Related Questions