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

  • jQuery, Each() and Async GetsjQuery, Each() and Async Gets One of the things to keep in mind when using jQuery is that nothing is a blocking call.  Sure, there is a certain sequence to when things operate.  But, to be safe, you should always a...
  • jQuery – class manipulationjQuery – class manipulation So, now that we've fully exhausted the topic of how to select elements using jQuery, what can we do with it? Well, one thing we can do is use the two built-in methods, addClass and removeClass, ...
  • jQuery – Creating Plug-insjQuery – Creating Plug-ins Last week we looked at how to have jQuery execute our own functions. I suggested at the time that if you were going to need to use that function in multiple applications, you might want to consid...
  • jQuery, bgiframe and IE6 z-order hacksjQuery, bgiframe and IE6 z-order hacks Well, it probably looks like an odd title.  But let's face it: we still have to support IE6 for some of our clients no matter how much we don't like it or it shouldn't be.  And one of the most fru...
  • jQuery GUI – DragjQuery GUI – Drag About a year and a half ago I helped develop an application that required drag and drop functionality.  We used the MS-AJAX framework to implement it at the time because it was available and did w...