Does document ready interfere with referencing external javascript functions? - javascript

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

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

Call Variable Function from External JS File

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

Executing separate .js files

I am trying to learn how different .js files can be included in a HTML file, so that my code becomes more modular. I am following this page Can we call the function written in one JavaScript in another JS file?. I am confused at one point, that if I include files like this:
<script language="javascript" src="a.js">
<script language="javascript" src="b.js">
If a.js contains:
function alertOne() {
alert("one");
}
and b.js contains:
function alertTwo() {
alert("two");
}
then do I need to separately call the functions in HTML file or just including the files like <script language="javascript" src="b.js"> this, would execute alertTwo() function?
Your JavaScript files are just declaring the functions. If you want them to actually execute then yes, you'd need to call them at some point. Whether that's inside another .js file, inside a <script> tag in your HTML page, or as part of an event handler on an element, is up to you and depends on what exactly you want.
The code
function alertTwo() {
alert("two");
}
declares a function that can be called later
The code:
function alertTwo() {
alert("two");
}
alertTwo();
declares a function, and then immediately calls it.
The code:
(function alertTwo() {
alert("two");
})();
declares a function that immediately calls itself.
It doesn't matter if your code is directly in the HTML file, or included via script tag. Nothing is "executed" or done special via script tag. It's effectively like saying "paste the stuff from that file here."
The function alertOne() in a.js can be called from b.js if both a.js and b.js are included in your HTML.

Why is script ordering important when assigning a function to window.onload?

I have a website with three files:
index.html
<html>
<head>
<script src="First.js"></script>
<script src="Second.js"></script>
</head>
<body></body>
</html>
First.js
window.onload = Main;
Second.js
function Main() { var foo = 1; }
When I open the page, I expect the variable 'foo' to be set to '1'. Instead, when I open the page, it breaks indicating 'Main is not defined' and 'Main()' is never called.
If the '.onload' event for the window isn't supposed to fire until the page is fully loaded and thus assumingly both scripts have been loaded, why doesn't the window object have a reference to the 'Main()' method in 'Second.js'? Should 'Main()' be a globally accessible function?
NOTE: I realize I can change the order in which I load the scripts and then my code would work, but that's not the purpose of my question. What I really want to do is validate my assumption.
It doesn't work because the code in <script> elements are run sequentially and independently (this assumes synchronous scripts, the default). That is, two different <script> sections cannot forward-reference each other. Now, JavaScript "hoists" function name () {} constructs within the same context, so this would have worked "out of order" in a single <script>.
Preamble / warning:
Consider not using onload. If something else tries to use it (onload), then something will likely break. (I recommend jQuery because it "gets this right" and "is so darn easy"... then again, so do many other frameworks. Pick one :-)
For instance, this would work in jQuery:
jQuery(function () { Main() })
Explanation of why it works (and how to fix it without reordering scripts or using jQuery):
Note that in this case the jQuery internal event handler is called, which calls the anonymous callback, which then calls Main (which is now resolves to a function-object). The "similar" code here would be:
window.onload = function () { Main() }
These work because Main is not evaluated until the onload has occurred, in which case all the [synchronous] <script> elements have been executed. (Please see my comment as to what it means to evaluate Main.)
On the other hand, window.onload = Main (or jQuery(Main)) evaluate Main right-then and use the resulting value; as others have noted, Main is not set ("is undefined") at this point due to the ordering of the <script> elements (they run sequentially).
Please refer to the note at top as to why to not to use onload directly ;-)
Happy coding.
The second script file should be included first! That's where the function is defined. You can't reference it in the first script until it's not loaded.
The Main() function doesn't exist until Second.js has been loaded, so if you're loading First.js first there's no function-object to use in window.onload = Main; (Main is undefined). Load Second.js first if you aren't already.

Scope of my jQuery function?

I have a file called function.js which has all my jQuery for my aplication which looks like this
$(document).ready(function(){
insert_initial(); //first time to the page, insert into cart and set the subtotal originally
function update_gallery(product_id){
...
}
function update_prices(product_selector){
...
...
}
function insert_initial(){
...
}
$('.trigger').click(function(){
$('.stations').find(".drop-down").slideToggle();
return false;
});
...
...
On the top of the file i have my function call insert_initial(); which gets run on the initial load....and this works great..My problem is that i now need to include this js file on my php pages say 1.php and 2.php and 3.php and 1.php is the only one that needs the insert_initial(); ....so i was thinking of the best way to do this. I assumed taking out the function call out of the functions file and putting it into a separate file
<script src="/someting/js/functions.js" type="text/javascript"></script>
<script src="/someting/js/functions_insert.js" type="text/javascript"></script>
and in my functions_insert.js file i would have only
$(document).ready(function(){
insert_initial(); //first time to the page, insert into cart and set the subtotal originally
});
but that didnt work either...any ideas on how to fix this
This checks to make sure that the location of the current page includes "1.php" before calling insert_initial():
if(window.location.href.indexOf('1.php') != -1)
insert_initial();
I would recommend having your definitions and executions separate in this instance. You don't need to define your functions inside of jQuery's DOM ready event. But it is also good to namespace them as mentioned. A common paradigm I follow is like so:
functions.js
(function($, window, undefined) {
function update_gallery(product_id){
...
}
function update_prices(product_selector){
...
...
}
function insert_initial(){
...
}
window.MyApp = {
update_gallery: update_gallery,
update_prices: update_prices,
insert_initial: insert_initial
};
})(jQuery, window);
1.php
<script src="functions.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
MyApp.insert_initial();
});
</script>
Now you can include your definitions as needed, and call them as necessary.
Try namespacing your functions and attaching them to a nice global object.
window.MyApp = {};
MyApp.insert_initial = function(){
};
Then you can access it from wherever you need, provided it's included earlier in the page.
Edit:
If this doesn't work, you've got an error elsewhere in your code - load order, perhaps? Either method you've described to invoke the function is fine, just make sure it's defined when you invoke it.
Your functions defined in functions.js are only visible in the scope of that document ready function. A simple case where it doesn't work:
(function() {
function square(x) {
return x*x;
}
})();
alert(square(2)); //Fails, since square is not in scope
The easiest way to fix this is to declare your functions in the global namespace:
function square(x) {
return x*x;
};
alert(square(2)); //4

Categories

Resources