Call Variable Function from External JS File - javascript

I was trying to call the function outside js file, but that function is declared in variable, something like this below
external.js is the third party library which i shouldn't edit
jQuery(function(){
var submit_clicked={
cart_submit: function() {
alert("yes variable function is have scope outside");
}
}
});
In my side i call internal javascript something like
jQuery(function() {
alert(submit_clicked.cart_submit);
});
it denotes
Reference Error: submit_clicked is not defined
not sure how to overcome this issue. Can anyone suggest some ideas will be great :)
Here is my fiddle.
https://jsfiddle.net/rr2v4fhb/
FYI: I call my script next to the external js but still that scope is not available.

The problem lies in the external.js file. Declare the variable outside the jquery() handler and that should solve your issue!
If the external file is non-editable, then you cannot access the variable function due to its scope which is local (what you need is a global variable).

Related

Calling function/nested function from external js file

I'm having some issues with running some functions from an external js file.
The html includes:
<script src="js/file.js"></script>
<script>
$("#center-button").click(function() {
explodePage("center");
});
</script>
The js file includes:
var explodePage = function(button) {
//code here
aboutPage();
}
var aboutPage = function() {
//code here
}
The explodePage function runs fine, but as soon as it reaches the call to the nested aboutPage function, it starts throwing these uncaught typeerrors at me. It works fine if I don't use an external js file and just put everything into the html. Pretty new to this so probably missing something obvious in scope or something. Any solutions?
Declare the function's definition as below:
function explodePage(button) {
//code here
aboutPage();
}
function aboutPage() {
//code here
}
Explanation:
When you use the var keyword for declaring functions, the execution of JS happens as when the variable is initialized, you cannot reference or use variable's before declaration. In contrast with the name function defintion JS interpreter first picks the enclosed functions before execution and initializes it before the code execution. This is called AST- Abstract syntax tree that is followed by JS interpreters.
Also Remember:
Also bind your Jquery code inside a Jquery document ready function, just to make sure the Jquery and the DOM elements are available for the bindings.
It's not a good a idea to pollute the global window object with variables, since there can be collisions. And immediately-invoked function expression is a good solution for this.
(function(){
//You can declare your functions in here, and invoke them below
$( document ).ready(function() {
//Check that the DOM is ready, in order to manipulate it an add events
$("#center-button").click(function() {
explodePage("center");
});
});
})($); //Notice that we are injecting a dependency, in this case jQuery

How to define global function inside document.ready?

I want to define a global function inside document.ready which need to be called outside document.ready. I tried to define a function as
var global_fn={};
$(document.ready).function(){
global_fn.my_function=function(){
console.log('my function');
};
global_fn.my_function();
}
global_fn.my_function();
The function call global_fn.my_function(); inside document.ready works well, but outside it throws error: Uncaught TypeError: global_fn.my_function is not a function. What things I am missing?
NB. The reason for defining function inside document.ready is because of third party api I am using, which works only after dom is ready and the reason for making it global is because I want to call it in another js file.
The reason it doesn't work outside the document.ready function is that when it's out in the js file like that, the function gets executed before it gets created in document.ready.
It will be available in your other JS files as long as they don't try to access it before 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/

Does document ready interfere with referencing external javascript functions?

When the following scripts are run, I get no alert.
When I remove $('document').ready, I do get the alert.
Does $('document').ready pose a problem to referencing functions in an external js file?
If so, why?
scriptOne.js
$('document').ready(function(){
function derp () {
alert('derp');
}
});
scriptTwo.js
$('document').ready(function(){
derp();
});
derp.html
<script src='scriptOne.js' type='text/javascript'></script>
<script src='scriptTwo.js' type='text/javascript'></script>
Keep in mind that javascript has function scope. So, in the example, the function derp() only exists inside of the anonymous function defined in scriptOne.js.
Which means it can't be accessed from scriptTwo.js
If you remove $('document').ready from the first file and just define the fucntion it will be defined globally.
Also, (as others have mentioned) you don't need single quotes around document
More information on function scope

What must an external JavaScript file look like to avoid global variables and methods?

I have the following piece of code on my page:
<script src="/Assets/JavaScripts/myJavaScript.js" type="text/javascript"></script>
<script type="text/javascript">
testAlert();
</script>
And in myJavaScript.js I have the following:
(function () {
function testAlert() {
alert('test alert');
}
})();
It's not calling testAlert. Not sure what I am doing wrong here? I'm trying to avoid global variables and methods. I did something similiar in jQuery and it worked, it just required a $ at the start of the external file. Can somebody please explain what I am doing wrong here and how to make sure I follow best practices?
I put your code in my environment and checked, I got error in mozila error console.
So, Please check it there.
you should put only below javascript function in myjavascript.js file.
function testAlert() {
alert('test alert');
}
Your function in the js-file isn't returning anything. To avoid global variables you could create one global namespace (-like) variable:
var myNS = (function () {
function testAlert() {
alert('test alert');
}
return {testAlert:testAlert};
}());
Now you can use myNS.testalert() in your inline javascript.
JS is made in such a way that you really can't totally avoid globals. (Well, you can, sort of. If you never give anything a name. But that tends to cause more problems than it solves.) When you call testAlert from some other script, you're operating under the assumption that testAlert is global. If it weren't, you couldn't just call it from anywhere like that.
You can minimize the chance of collision, though, by adding your stuff to an object that serves as a namespace, like so:
// don't clear it out if it already exists.
// that way all of your scripts can use your namespace, if you want.
// what you're really trying to protect against, are strangers picking names
// like yours.
if (!window.myNamespace) myNamespace = {};
// example function
myNamespace.testAlert = function() { alert("test alert"); };
myNamespace.testAlert();
This way, the only name that has a good chance of conflicting is myNamespace.
I was going to show an example of a namespaced global...but ya know what? A namespaced global is still a global. Global variables are something you want to try and get rid of in most cases.
You need some sort of global variable so that you can access the method you're looking for. The fact that you have <script>testAlert()</script> means you expect testAlert() to be defined in the global namespace.
What I like to do (especially when using YUI, which you have tagged this question with), is to create a global object that acts as a utility class.
var page = {
init: function() {
// Do some initialization...
},
testAlert: function() {
alert("Test Alert");
}
};
After you do that, you can use the single global "page" variable to access everything you need.
// e.g.
page.testAlert();
// or...
Y.on("domready", page.init, page);
Again, for the second example I'm assuming you're using YUI, since you tagged this question with it.

Categories

Resources