Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it better to encapsulate functionality in a jQuery plugin or vanilla JavaScript function?

Let's say i have some bit of JavaScript which will modify the DOM, perhaps hide/show a form field or something like that and let's assume I want to execute this task on multiple pages, but only once or twice per page.

Is it better to encapsulate this functionality into a jQuery plugin, or a vanilla JavaScript function?

Essentially, is this:

jQuery.fn.toggleFormInput = function() {
    // Stunning JavaScript/jQuery magic here
}

better or worse than this:

function toggleFormInput () {
    // Stunning JavaScript/jQuery magic here
}
like image 206
ProcessEight Avatar asked Jul 25 '11 13:07

ProcessEight


1 Answers

It really depends on the rest of your site. If you are using the rest of the jQuery library, if you are then you can utilise jQuery specific functions inside of your own - each() is a good example. That kind of jQuery magic might allow you to write less code. I would look into doing some kind of benchmark where you write both and see which one executes faster.

But if you want a function that you can move from site to site without dependancies it might be a good idea to go it alone with Javascript. Personally I would be inclined to use plain Javascript so that I wasn't bound down to any 1 library, but that's your choice.

like image 89
Tom Walters Avatar answered Sep 27 '22 23:09

Tom Walters