6

I have a function that accepts the element it needs to operate on as a parameter element

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

and I call it this 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 where it accepts its object as a param to this format. How do I do it

$('#sectionOne').changeColor();
$(document).changeColor();

2 Answers 2

6

As Nikita said, you need to write a jQuery plugin. Here's a basic example, which 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);
Sign up to request clarification or add additional context in comments.

3 Comments

I agree with your above answer. But what, If i'm not interested to use jquery into my project then? Actually I'm using Angular JS. Waiting for your reply...
@vijayshegokar I recommend that you create a new question so that people can get points for answering it.
I have created a new question. Please check stackoverflow.com/questions/29504841/…
1

You want to create a jQuery plugin. jQuery folks provide a tutorial for that.

If you don't like reading much, you can practically copy-paste maxHeight example and replace logic inside.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.