function registering after document.ready [duplicate] - javascript

This question already has answers here:
Why can I not define functions in jQuery's document.ready()?
(6 answers)
Closed 8 years ago.
Im trying to understand how the browser works if it has 2 document.ready functions within it.
Sample code: Here printtest() module has a alert statement within my first document.ready function and its been called below but I don't see any action..
$(document).ready(function(){
function printtest(){
alert('Hi')
}
})
$(document).ready(function(){
printtest()
})
http://jsfiddle.net/7FuLc/1/
Since it has 2 document.ready function, how does the browser registers this function?

That code will not work because because javascript function creates a new scope variable every time it is declared. See the following:
$(document).ready(function(){
function printtest(){
alert('Hi')
}
})
$(document).ready(function(){
printtest() // ReferenceError, printtest undefined
})
compare this to
function printtest(){
alert('Hi')
}
$(document).ready(function(){
printtest() // alerts 'Hi'
})
$(document).ready(function(){
printtest() // alerts 'Hi'
})
This way, both $(document).ready(function(){}) understand what printtest is.
To solve your problem, here is the modified code,
var printtest;
$(document).ready(function(){
printtest = function (){
alert('Hi')
}
})
$(document).ready(function(){
printtest(); // alerts 'Hi'
})
Now this will work the way you intend it to be because you declare the variable outside the function. This is due to closure (closure is inner javascript function, meaning that any outside variable can be accessed inside the inner javascript function).
In conclusion, if you want a function that is accessible across different functions, declare it outside so that any other closure will be able to access it.

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().

Why is a javascript function unaccessible from another script file? [duplicate]

This question already has answers here:
What is the scope of variables in JavaScript?
(27 answers)
Closed 5 years ago.
I have a problem I've been searching SO for answers to, but nothing seem to do it for me. I've referenced a question that mimics my problem but the solution still don't solve my problem.
Accessing function in another .js file with $.getScript
My problem is as I've mentioned similar. I can't access a method inside a script file from another script file. These are my codes:
page.js
$(document).ready(function () {
$.getScript('script.js').done(function () {
$('#build').append(literals.test()); // $('#build') is a span tag in the HTML-file.
}).fail(function () {
console.warn('Unable to load script file.');
});
});
script.js
(function ($) {
var literals = {
test: function () {
return 'Hello world!';
}
};
})(jQuery);
This still returns the following error even though I've built it almost exactly the same way as in the answer of the referenced question.
Uncaught ReferenceError: literals is not defined at Object.<anonymous>
What am I doing wrong here?
Because when you create a closure, anything inside of it is only visible to other things in that scope.
In JS, all functions are closures.
(function(){
// this is a closure
})()
If you want to be able to get the literals functions from outside of the closure, one option is to return it from the function...
const literals = (function($){
return {
test: function () {
return 'Hello world!';
}
};
})(jQuery);
console.log(literals.test());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

jQuery function scope confusion [duplicate]

This question already has answers here:
What is the purpose of the var keyword and when should I use it (or omit it)?
(19 answers)
Closed 8 years ago.
EDIT I want the function to be globally accessible
Why does myfunction0 work in the dom ready call and myfunction1 does not work?
external.js file
(function($) {
// functions defined like that works
myfunction0 = function() {
console.log("hello world");
}
// functions defined like that do not work
function myfunction1() {
console.log("hello world");
}
})(jQuery);
index.html
<script>
$(function () {
myfunction0(); // works
myfunction1(); // does not work not defined
})
</script>
Does the first function definition get a global scope whereas the second only a local 'in file' scope?
function myfunction1() { }
will be local to the scope in which it's defined. Not the file, but the anonymous function it's wrapped in.
myfunction0 = function() { }
declares a variable (which happens to be a function).
Since there's no var attached, that variable gets global scope.
You have not declared the myfunction0 using the var keyword so it has been declared in global scope. function declarations are tied to the scope in which they are declared.
If you add the var keyword to your myfunction0 (as you should) you'll see that neither function will be accessible:
var myfunction0 = function() {
console.log("hello world");
}
Example fiddle

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/

call a function from javascript in jquery [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
How do i call a function in jquery that i have written? The following code that I tried is not working.
<script>
$(function(){
function afunction() {
alert("me");
}
});
</script>
<script>
afunction();
</script>
jQuery is simply a JavaScript library. You can mix regular JavaScript in without requiring everything use the jQuery $(). Because of function scope, wrapping your function in the $(document).ready function will make it unavailable to be called outside of the ready function.
Try changing your code to this:
function afunction() {
alert("me");
}
If you need to define a function inside of a jQuery function or event handler, that's fine too. Although it's been pointed out that you can't call this function outside of the ready event handler, I would like to demonstrate that jQuery and JavaScript are not separate and can be mixed. For instance:
$(document).ready(function() {
function afunction() {
alert("me");
}
afunction();
});
Just to clarify, $(function() is another form of $(document).ready().
As Vedant mentioned, usually you cannot call a function (JS/jQuery) from outside the function in which it is defined.
You should probably declare function afunction() outside of $(function() method, alternatively you could declare it as
global function afunction() for universal access.
okay. Here is What I Meant.
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 afunction() {
alert("me");
}
window.afunction=afunction; //NOTE THIS, IT IS IMPORTANT.
});
Now you can access it elsewhere in your JS.
Here is working Fiddle
Hope it'll help you! cheers :)..

Categories

Resources