3

What is wrong with this code?

$(function() {
    function testfunction() { $(this).addClass('testing');}
    $('.tester').testfunction();
});
2
  • That's not how you make a jQuery plugin. Right now you're just creating a normal JavaScript function. That doesn't make jQuery aware of it. Commented Feb 14, 2011 at 10:30
  • @K Ivanov: Extend the jQuery object with custom functionality, from the looks of it. Commented Feb 14, 2011 at 10:32

1 Answer 1

13

testfunction() is not added to the jQuery function stack.

If you want to be able to call it on an arbitrary object, you should add it to the jQuery function stack:

$.fn.testfunction = function() {
   this.addClass('testing');
};

$('.tester').testfunction(); // success!

You should take a look at jQuery's Plugins/Authoring page for more information on how to properly write plugins.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. How do use variables that increment on every eliment the function is applied to? for example: $.fn.testfunction = function() { incrementthis++; this.append(incrementthis); this.addClass('testing'); }; $('.tester').testfunction(); // success!
You should use this.each(function() {}); inside the function. For more info, I really encourage you to read the docs.jquery.com/Plugins/Authoring page. It will help you understand the subject better.

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.