Is this how you define a function in jQuery?
$(document).ready( function () { var MyBlah = function($blah) { alert($blah); }; });
Now to call the function I do:
MyBlah('hello');
First of all, your code works and that's a valid way of creating a function in JavaScript (jQuery aside), but because you are declaring a function inside another function (an anonymous one in this case) "MyBlah" will not be accessible from the global scope.
Here's 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) a desirable behavior since we do not pollute the global namespace, so if your function does not need to be called from other part of your code, this is the way to go.
Declaring it outside the anonymous function places it in the global namespace, and it's accessible from everywhere.
Lastly, the $ at the beginning of the variable name is not needed, and sometimes used as a jQuery convention when the variable is an instance of the jQuery object itself (not necessarily in this case).
Maybe what you need is creating a jQuery plugin, this is very very easy and useful as well since it will allow you to do something like this:
$('div#message').myBlah("hello")
See also: http://www.re-cycledair.com/creating-jquery-plugins
No, you can just write the function as:
$(document).ready(function() { MyBlah("hello"); }); function MyBlah(blah) { alert(blah); }
This calls the function MyBlah
on content ready.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With