tags:

views:

191

answers:

5

What is wrong with this syntax?

<script>
jQuery(function() {
    jQuery.fn.myfunction(myparam) {
     alert(myparam);
     return 0; // return jQuery?
    }
    myfunction('Hello World');
});
</script>

I'm trying to learn how to extend jQuery.

+1  A: 

From the documentation...

jQuery.fn.extend({
  check: function() {
    return this.each(function() { this.checked = true; });
  },
  uncheck: function() {
    return this.each(function() { this.checked = false; });
  }
});

See more here.

Chalkey
Chalkey: I am coming to you for help because I don't understand the jQuery documentation.
cf_PhillipSenn
What you want is to give the jQuery.fn.[you_function] a function... such that jQuery.fn.example = function() { document.write('example'); return this; } ... The returning this will allow you to chain jQuery objects together. You have probably seen something like $('#div#').hide().show('slow'); etc.
Chalkey
I was looking for the exact syntax because it seems that you can do anything you want in jQuery - all you need is a couple of squiggly lines, curly brackets, braces and parentheses and bam! There you have it.
cf_PhillipSenn
+5  A: 
jQuery.fn.myfunction(myparam) {

should be

jQuery.fn.myfunction = function(myparam) {

as you are assigning the property myfunction of object jQuery.fn a value of function () {...

cobbal
+1, this is correct
Jason
+1  A: 

Here's a link: jQuery

Jacob Relkin
Jacob Relkin: I am coming to you for help because I have read the documentation and do not understand it.
cf_PhillipSenn
+3  A: 

A method defined via jQuery.myFunction is a "static" function. You call it by doing $.yourFunction, and it's not tied to a result set.

Conversely, a function defined on jQuery.fn.myFunction is a tied to a result set; if you do "this" within that function, you'll get the jQuery object that was used to call it. In other words, if you do $("P").myFunction() "this" in my Function will be $("P").

machineghost
+3  A: 

Your syntax is trying to call a method called myFunction on the jQuery.fn reference.

To extend the jQuery object, you want this syntax:

<script>
jQuery(function() {
    jQuery.fn.myfunction = function(myparam) {
        alert(myparam);
        return this; // returns the current jQuery object.
    }

    // Select something with jQuery using the $() function here.
    $().myfunction('Hello World');
});
</script>
Programming Hero
You are my hero.
cf_PhillipSenn