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.
Related
I am getting this error validate_allocation is not defined when trying to execute a function from a static file. Any idea why?
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="static/main.js"></script>
<script>
validate_allocation();
</script>
main.js
$(function() {
alert('test'); // I can see this, so the file is imported for sure
function validate_allocation(){
alert('test');
}
});
The purpose of $(function() { ... }); is to run the code inside once the page has finished loading. As others have said, you're defining a function not only after the page has finished loading (and therefore after the call is made in your HTML file), but it is also limited to the scope of that block. It can safely be moved out of the block:
// Declare function at the root of the document and make it accessible to the HTML page
function validate_allocation(){
alert('test');
}
// Actions to perform when the page has completed loading
$(function() {
alert('test'); // I can see this, so the file is imported for sure
});
Remove the Validate_allocation function from jquery onload function. Since you are writing in that function it will be scoped to that function only.
function validate_allocation(){
alert('test');
}
$(function() {
alert('test'); // I can see this, so the file is imported for sure
});
This will make the function globally accessible
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
I am having a custom.js file in app/assets folder which was created when I generated a custom controller. Now i have created a custom_action.js.erb file under app/views/customs which is a part of custom controller views. This custom_action.js.erb file is used to handle ajax respose.
Now the problem that I face is that I cant access functions defined in custom.js to custom_action.js.erb. This is my custom.js file.
$(document).ready(function(){
function someFunction() {
// do something
}
}
And this is my custom_action.js.erb file.
$('#selector').onClick{
someFunction(); //This is where I want to access the custom.js function
}
Right now I am repeating the function in both custom.js and custom_action.js.erb file. Is there a way to avoid this repeat and make the function accessible when I define it in custom.js file.
You don't need to wrap a function in $(document).ready. When you do that it only has scope within that particular ready callback handler function. Also jQuery has no onClick method.
$(document).ready is only needed for code that will run immediately on page load that will need to locate elements in the page.
function someFunction() {
// do something
}
$(document).ready(function(){
$('#selector').click(function(){
someFunction();
});
/* or */
$('#selector').click(someFunction);
});
I have a number of javascript plugins which are included in my HTML file, and are included successfully because I have checked.
Heres the problem;
Basically I want to create a function outside the HTML file, and then inside the HTML file load that particular function when the document is ready.
this is the function (outside) of the HTML file. As a stand alone JS file:
function do_anchor_scrolling() {
$('#back_to_top').anchorScroll();
$("#landing_link").anchorScroll();
$("#menu_link").anchorScroll();
$("#sauces_link").anchorScroll();
$("#ranches_link").anchorScroll();
$("#order_link").anchorScroll();
$("#about_link").anchorScroll();
$("#franchise_link").anchorScroll();
});
the function is called do_anchor_scrolling
How in JQuery can I say when the document is ready perform the do_anchor_scrolling function.
When the document is ready, call the function.
$(document).ready(function(){
do_anchor_scrolling();
});
Pass it as a handler into the ready method:
$(document).ready(do_anchor_scrolling);
Or even shorter:
$(do_anchor_scrolling);
Notice the function is not executed right there (no invoking parenthesis) - the function object itself is passed into the ready function.
You can just do:
$.getScript("yourfile.js");//it grabs and executes yourfile.js
//so your function is now defined
do_anchor_scrolling(); //and you can call it
You can go without the $_getScript() call by just putting yourfile.js inside a <script> tag in <head>.
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