Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use jQuery plugins over javascript functions?

Why would you use a jQuery plugin over a traditional javascript function? The only difference I see is you need to pass in a jQuery object into the js function... other that that, I don't see a huge difference, as it seems both can accomplish the same thing in similar steps:

        $(document).ready(function () {
            $('p').jQuery_greenify();
            greenify($('p'));
        });

        $.fn.jQuery_greenify = function () { 
            this.css("color", "green");
        };

        function greenify (el) {
            el.css("color", "green");
        }

I also find namespacing to be easier with javascript functions:

        var mynamespace = {

            greenify : function (el) {
                el.css("color", "green");
            }
        }
        mynamespace.greenify($('p'));
like image 491
user3871 Avatar asked Feb 25 '26 23:02

user3871


1 Answers

Usually, usefulness of JQuery functions is in chaining them. Just like you want to call:

string.substring(2, 5).startsWith("lol")

instead of

Util.StartsWith(Util.substring(string, 2, 5), "lol")

It's easier to read that way. In fact, I think that second function might still need a "return this" to be useful?

It may depend on the context - some operations are very much tied to an element or set of elements, while others just make more sense standing on their own - thus, your approach of namespacing would be just fine. It's partially coding style.

A disclaimer - I'm not as experienced with writing JQuery plugins, this is just my general observations based on JS language design.

like image 145
Katana314 Avatar answered Feb 28 '26 12:02

Katana314



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!