jQuery – Calling Your Own Functions

color-02 While jQuery has a lot of functionality built into it, you may find that you have a need to implement your own functions and attach them to the jQuery framework in some way.

There are two ways to do this. You could extend the framework by creating a plug-in or you could use one of the built-in functions and simply tell it to call your function.  For one-off implementations, using the function is easier and recommended.  But if you are going to reuse the code between multiple projects you’ll want to implement the added functionality as a plug-in.

Today, we’ll look at using the built-in function.

The method we will be using for calling our own functions is the .each() method.  Each takes a function pointer that accepts a zero based index into the list we are each()ing over.

The other thing you need to know is that the selector $(this) represents the current item you are iterating over.  In practice, the index parameter gets ignored and we use $(this) almost exclusively.

Finally, since this is a one-off implementation, you will probably just use an anonymous function to implement your each so that your code ends up looking something like this:

$('selector').each(function(index) {
    $(this).doSomethingHere();
});

 

Other post in jQuery

Related Post

One Response to “jQuery – Calling Your Own Functions”

Leave a Reply

Comment Policy:

  • You must verify your comment by responding to the automated email that is sent to your email address. Unverified comments will never show.Leave a good comment that adds to the conversation and I'll leave your link in.
  • Leave me pure spam and I'll delete it.
  • Leave a general comment and I'll remove the link but keep the comment.

Notify me of followup comments via e-mail

Bear