Is this how you define a function in jQuery?

Is this how you define a function in jQuery?

$(document).ready( function () { var MyBlah = function($blah) { alert($blah); }; }); 

Now to call the function:

 MyBlah('hello'); 
+45
javascript jquery
May 25 '09 at 18:22
source share
6 answers

First of all, your code works and what a valid way to create a function in JavaScript (aside from jQuery), but because you declare a function inside another function (anonymous in this case), "MyBlah" will not be accessible from the global scope.

Here is an example:

 $(document).ready( function () { var MyBlah = function($blah) { alert($blah); }; MyBlah("Hello this works") // Inside the anonymous function we are cool. }); MyBlah("Oops") //This throws a JavaScript error (MyBlah is not a function) 

This is (sometimes) desirable behavior, since we do not pollute the global namespace , so if your function does not need to be called from another part of your code, this is the way to go.

Declaring it outside an anonymous function places it in the global namespace and is accessible to it everywhere.

Finally, $ is not required at the beginning of the variable name, and is sometimes used as a jQuery convention when the variable is an instance of the jQuery object itself (not necessary in this case).

Perhaps you need to create a jQuery plugin, it is very easy and useful, as it will allow you to do something like this:

 $('div#message').myBlah("hello") 
+84
May 25 '09 at 18:38
source share

No, you can simply write a function as:

 $(document).ready(function() { MyBlah("hello"); }); function MyBlah(blah) { alert(blah); } 

This calls the MyBlah function in the finished content.

+39
May 25 '09 at 18:25
source share

No.

You define functions in exactly the same way as in regular javascript.

 //document ready $(function(){ myBlah(); }) var myBlah = function(blah){ alert(blah); } 

Also: no need for $

+14
May 25 '09 at 18:25
source share

You can extend the jQuery prototype and use your function as a jQuery method.

 (function($) { $.fn.MyBlah = function(blah) { $(this).addClass(blah); console.log('blah class added'); }; })(jQuery); jQuery(document).ready(function($) { $('#blahElementId').MyBlah('newClass'); }); 

Additional information on the jQuery prototype extension: http://api.jquery.com/jquery.fn.extend/

+8
Apr 09 '14 at 11:37
source share
 jQuery.fn.extend({ zigzag: function () { var text = $(this).text(); var zigzagText = ''; var toggle = true; //lower/uppper toggle $.each(text, function(i, nome) { zigzagText += (toggle) ? nome.toUpperCase() : nome.toLowerCase(); toggle = (toggle) ? false : true; }); return zigzagText; } }); 
0
Feb 16 '17 at 12:22
source share

This way you define an anonymous function that is called when the document is ready.

-5
May 25 '09 at 18:25
source share



All Articles