Tutorials JavaScript Custom jQuery Function

Custom jQuery Function

Today's tutorial will be about how to create your function in jQuery. I know there are a lot of plugins out there but there's always one feature that you need and they don't have. Today, you make your own custom function.

Creating your first function

(function($) {      $.fn.myfunc = function() {        // Loop through objects    this.each(function() {            $(this).click(function() {        var text = $(this).text();        alert("You clicked on " + text);      });          }); // End object loop        return this;      }  })(jQuery); 

How do you call it?

Just include jQuery and your function code, then call the function.

<script src="http://code.jquery.com/jquery-latest.js"></script><script type="text/javascript">(function($) {      $.fn.myfunc = function() {        // Loop through objects    this.each(function() {            $(this).click(function() {        var text = $(this).text();        alert("You clicked on " + text);      });          }); // End object loop        return this;      }  })(jQuery); $(document).ready(function() {        $("a.alert").myfunc();});</script>

What can you do with this?

Anything that you can do with normal jQuery functions. Putting it into a function just makes it easier to organize or distribute.

Demo

That's all for this tutorial. Now you should go out and try your new jQuery abilities. See you next time on PHP Trainee.

Posted by on . Category: JavaScript


Comments

No comments posted yet

You need to register or login to post new comments.