Are js functions defined in modules accessible outside that module? - javascript

I current have some code that looks like this:
// when the document is ready
execute myFunction();
(function($){
function myFunction()
{
// code
};
})(jQuery);
The console is saying that myFunction is not defined...why?

It's not accessible because you've put your function inside another self-invoking function, and the call to it is outside that.
Your comment states that you want the call to myFunction() to happen on load, which if your current code worked, would not be the case anyway. It would call the function before DOMReady.
To get the behaviour you want, place the function call within the SIF:
(function($){
myFunction();
function myFunction() {
// code
};
})(jQuery);

Related

want to use functions within ready jQuery method

I have a similar question before, my question was about how to access all the JavaScript functions in the web browser console even if they were within window.onload = function() {// code and functions} , but this time I want to do the same thing with jQuery:
$(document).ready(function() {
// I want to access all the functions that are here in the web console
})
You can use the same syntax as in your previous question. Simply assign the function to the window.
The following example illustrates what I mean. Note that you do not need the setTimeout(), this is just for this example here to auto-execute the your_function() when it is defined.
$(document).ready(function() {
window.your_function = function(){
console.log("your function");
};
your_function();
});
// setTimeout() is needed because the $.ready() function was not executed when
// this code block is reached, the function(){your_function();} is needed because
// the your_function() is not defined when the code is reached
setTimeout(function(){
your_function();
}, 500);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Note 2: I suggenst not to define global functions in the $(document).ready() if there is not a good reason for it. You can define the functions outside and then call them in the $(document).ready().

Not able to define function

I am writing something like
(function($){
function showAlert(){
alert('test');
}
})(jQuery);
and when I tried to run showAlert(), it's saying showAlert() is not defined.
Can anyone suggest why ?
The scope of a variable in javascript is either
the global scope
the function in which it is defined
showAlert is a variable. It's only available in the scope of the external function you wrote.
If you want to define a function for the external scope, define it in the external scope.
I suppose you're calling that function outside IEFE function.
Calling it outside won't work as it is not in global scope. The IEFE is creating a closure of which , showAlert becomes a part and not of global scope which is window
Do this:
(function($){
window.showAlert = function(){
alert('test');
}
})(jQuery);
It doesn't make sense to put a function declaration inside IEFE unless otherwise it is a jquery plugin. So, just remove it:
function showAlert(){
alert('test');
}
You're Creating A function inside a self executing anonymus function ie. $(document).ready() or $(function()....
So your function is in local scope of that function. Simply Means You cant access that in outside of that function.
So to make it accessible just make it global.
In JavaScript window is global object. So to make your function global, use that object as follows:
$(document).ready(function() {
function showAlert()() {
alert('test');
}
window.showAlert=showAlert(); //NOTE THIS, IT IS IMPORTANT.
});
Now you can access it elsewhere in your JS.
Here is working Fiddle
Hope it'll help you! cheers :)..
If you want to extend jQuery with your function just add function to jQuery object.
Like this:
(function ($) {
$.extend({
showAlert: function () {
alert('test');
}
});
}(jQuery));
Separate this code into file with name jquery.showAlert.js, include it after jquery library
and after this you can use function in this way:
$.showAlert()
Best regards.
This should work!
function showAlert(x) {
alert(x);
}
showAlert($('#anyElementId').val());
Assign the variable X for function and your alert. Then pass your element val into your function call.
Demo: http://jsfiddle.net/94ZtT/

Where should I put functions in Javascript code?

I have the following code:
(function($) {
"use strict";
$(function() {
// jQuery code here, eg:
$('body').css('padding-top', $('.nav').height());
// I want to call that func here...
});
}(jQuery));
And custom function:
function xyz(a,b) {
// do something with "a" and "b"
}
Where should I place my custom function? Before (function($) {, before $(function() {, or inside $(function() {});?
The difference is the scope.
Location : Scope
----------------------+--------------------------------------------------------
before (function($) { : in global scope, easy to call & modify from everywhere
before $(function() { : in "source module" scope / jQuery closure
inside $(function() { : in "$(function" scope
So that choice gives you the means to organize the access to your code.
In most cases you want to hide stuff to prevent unintended interactions, but in some cases (e.g. log function), you want to have access from everywhere in your web application.
If you do not need to call xyz() from outside $(function, keep it inside. If you do just need to call it within the module, keep it inside ( .. (jQuery)). If you need to call it from everywhere keep it outside in global scope.
Since you want to call the function inside the ready handler, declare it inside it
jQuery(function ($) {
"use strict";
// jQuery code here, eg:
$('body').css('padding-top', $('.nav').height());
// I want to call that func here...
xyz();
function xyz(a, b) {
// do something with "a" and "b"
}
});
But if you want to access xyz from outside the scope of the dom ready handler you will have to declare it outside the scope of the dom ready handler. Now the method is local to the dom ready handler and thus accessible only inside it.
Also as shown above you can shorten the use of IIFE and dom ready handler as shown above

How to reference functions with document ready?

I have some functions in a JQuery document ready method that I would like to reference from other external files, but I keep getting a function undefined. How can I make those global?
ex.
external file 1
$(function ()
{
function DoSomething()
{
Do something
}
});
external file 2
$(function ()
{
Call DoSomething()
)};
declare the functions outside the jQuery escope.
external file 1
function DoSomething()
{
Do something
}
external file 2
$(function ()
{
Call DoSomething()
)};
You can either define the function outside .ready() (as the other answers suggest), or you can take advantage of the fact that the window object is the global scope. So, you can make them global like this:
$(function(){
function doSomething(){
// …;
}
window.doSomething = doSomething;
});
Note that in this case they’ll only be defined after .ready() runs — if you want to use them immediately in another file (i.e. not inside an event handler or another .ready() function), this won’t work.
You probably want to define functions outside ready blocks. That does not hurt. Only executing a function outside a ready block can cause issues if it uses the DOM before it's ready.
Defining does nothing (yet), and as such does not use the DOM. So it does not need to be inside a ready block; doing so only constrains the places where you can access it, which is basically only a disadvantage.
external file 1
function DoSomething()
{
Do something
}
Whenever possible, declare functions outside of the ready check.
external file 1
function DoSomething()
{
Do something
}
external file 2
$(function ()
{
Call DoSomething()
)};

Do self executing functions run at dom ready?

Before I heard about self executing functions I always used to do this:
$(document).ready(function() {
doSomething();
});
function doSomething()
{
// blah
}
Would a self executing function have the same effect? will it run on dom ready?
(function doSomething($) {
// blah
})(jQuery);
Nope. A self executing function runs when the Javascript engine finds it.
However, if you put all of you code at the end of your document before the closing </body> tag (which is highly recommended), then you don't have to wait for DOM ready, as you're past that automatically.
If all you want is to scope your $ variable, and you don't want to move your code to the bottom of the page, you can use this:
jQuery(function($){
// The "$" variable is now scoped in here
// and will not be affected by any code
// overriding it outside of this function
});
It won't, it will be ran as soon as the JavaScript file is executed.
No, self-executing javascript functions run right there.
If you want to create a DOM ready function, write the following:
$(function() {
// this will run on DOM ready
});
Which is a shorthand of:
$(document).ready(function() {
});
No, the self-executing function run immediatly after you "declare" it on your code. Even if it's located on an external .js file.
In your example, there is a possibility that your function will execute and the value of jQuery is undefined. If you want your code to be executed on DOMReady, continue using
$(document).ready(function(){
doSomething();
});
or
$(function(){
doSomething();
});
or even
window.onload = function(){
doSomething();
}
$(document).ready(function() { ... }); simply binds that function to the ready event of the document, so, as you said, when the document loads, the event triggers.
(function($) { ... })(jQuery);
is actually a construct of Javascript, and all that piece of code does is pass the jQuery object into function($) as a parameter and runs the function, so inside that function, $ always refers to the jQuery object. This can help resolve namespacing conflicts, etc.
So #1 is executed when the document is loaded, while #2 is run immediately, with the jQuery object named $ as shorthand
$(document).ready(function(){ ... }); or short $(function(){...});
This Function is called when the DOM is ready which means, you can start to query elements for instance. .ready() will use different ways on different browsers to make sure that the DOM really IS ready.
(function(){ ... })();
That is nothing else than a function that invokes itself as soon as possible when the browser is interpreting your ecma-/javascript. Therefor, its very unlikely that you can successfully act on DOM elements here.
jQuery document.ready vs self calling anonymous function

Categories

Resources