How to turn a function from function (element) syntax into $ (element) .function () syntax

I have a function that takes an element in which it should work as an element parameter

 function changeColor(element){ $(element).find('.middleBox').each(function(){ $(this).//do some stuff that does not matter now; }); } 

and I call it that way

 changeColor($(document)); //this applies it to the whole document changeColor($('#sectionOne')); //this applies it to only part of the document 

I want to change it from the format in which it takes its object as a parameter for this format. How to do it?

 $('#sectionOne').changeColor(); $(document).changeColor(); 
+6
javascript jquery
source share
2 answers

As Nikita said, you need to write a jQuery plugin. Here is a basic example that should be enough for what you are trying to do:

 (function($) { $.fn.changeColor = function() { return this.each(function() { $(this).find('.middleBox').each(function() { $(this).//do some stuff that does not matter now; }); }); }; })(jQuery); 
+6
source share

You want to create a jQuery plugin. JQuery users provide a tutorial for this.

If you don't like reading a lot, you can practically copy-paste the maxHeight example and replace the internal logic.

+1
source share

All Articles