Let's say we have the following page:
<html>
<head>
</head>
<body>
<script src="jQuery.js"></script>
<script src="myFile.js"></script>
<script>
$(document).ready(function() {
test();
});
</script>
</body>
</html>
And myFile.js looks like this:
$(document).ready(function() {
function test() {
alert('Hello World!');
}
});
Then console.log will output the following error:
Uncaught ReferenceError: test is not defined
I'd rather not include my .JS files in <head> (which I think will solve the problem) since it is more clean to load it after HTML, in footer of page.
Any ideas how to wait for test(); to run, till myFile.js is loaded?
You need to define test on the global scope if you want to use it elsewhere. Also, you don't need to wait for the document to be ready if you're code is in the footer.
//$(document).ready(function() {
function test() {
alert('Hello World!');
}
// add it to global scope
// window.test = test;
//});
and
<script>
//$(document).ready(function() {
test();
//});
</script>
Related
There are two files here in the same folder.
I am trying to invoke a function named greet of app1 in app2.
app1.html
<script>
function greet() {
alert('hello from App1')
}
// greet() // commented out code
</script>
app2.html
<script type="text/javascript" src="./app1.html"></script>
<script>
function app2() {
alert('app2')
}
app2()
greet() // this line of code is not working
</script>
If you want to call the file in an another js file then you have to refer that file in the calling file.
Ex.
Refer the files in the head section.
<head>
<script src="File2.js" type="text/javascript"></script>
<script src="File1.js" type="text/javascript"></script>
</head>
you can have your body tag something like this:
<body>
<script type="text/javascript">
Method2(); // Where you want to call method from another JS.
</script>
</body>
then, using first file
File1.js
function Method1(number) {
alert("Method1");
}
File2.js
function Method2() {
Method1("Method1 is called in Method2");
}
I would recomend have separate external js files instead of an embedded <script> tag, but maybe this can help
How to include js file in another js file?
'turbolinks:load' is not getting triggered on the directly loaded pages but, on the pages loaded with turbolinks 'turbolinks:load' event is working fine.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://rawgit.com/turbolinks/turbolinks/master/dist/turbolinks.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<title>
test
</title>
<script>
function loadScript(src) {
if(!document.querySelector("script[src='"+src+"']")){
var n = document.createElement("script");
n.src = src;
n.async = false;
document.getElementsByTagName("head")[0].appendChild(n);
};
};
</script>
</head>
<body>
<p style='color:red'>
Hi Priority Rendering With inline css to improve start render
</p>
<script type="text/javascript">
loadScript("dynamic_load_turbolinks_script.js");
</script>
</body>
</html>
Code of dynamic_load_turbolinks_script.js
console.log('This file will contain all functionally required script');
document.addEventListener("turbolinks:load", function() {
console.log('Inside turbolinkss Load')
});
window.onload = function(){
console.log('Inside window onload')
};
document.addEventListener('DOMContentLoaded', function(){
console.log('Inside DOMContentLoaded')
});
$(document).ready(function() {
console.log( "Inside document ready" );
});
Browser Console output of above code is
dynamic_load_turbolinks_script.js:1 This file will contain all functionally required script
dynamic_load_turbolinks_script.js:6 Inside window onload
dynamic_load_turbolinks_script.js:12 Inside document ready
I know that the issue is because dynamic scripts are executed outside of DOM parsing but, is there any way to achieve the desired behavior?
Is it possible to call a function declared in a .js file from the body of the HTML. I'm assuming the reason it won't work is because the .js file is called after the function has been called in the HTML body. Is there a way around this.
I've had a look at some answers here, but can't seem to find what I'm looking for. My apologies if it's staring at me as a beginner I may not be using the correct terminology.
jqueryfunctions.js:
function someFunction() {
// do.something;
}
index.html:
<html>
<head>
<script type="text/javascript" src="//code.jquery.com/jquery-1.8.3.js"></script>
<script src="jqueryfunctions.js"></script>
</head>
<body>
<script>
someFunction();
</script>
</body>
</html>
Here is the full/actual .js file returnedMessage() is the function I was reffering to as someFunction().
The console error I'm getting is "returnedMessage() is not defined".
$(function(){
var timer = null;
function appendmessageBox() {
$('body').append('<div id="messageBox" class="datamessagebox"> </div> ');
}
// just before body tag.
appendmessageBox();
// makes MessageBox Disappear on MouseOver
$('#messageBox').on('mouseover click', function(){
$(this).fadeOut(300);
});
function returnedMessage(message) {
if (timer) {
clearTimeout(timer); //cancel the previous timer.
timer = null;
}
$( '#messageBox' ).css('display', 'inline-block');
timer = setTimeout(function(){
$( '#messageBox' ).fadeOut( 499 );
}, 5000);
$( '#messageBox' ).append('<msg>'+message+'<br /></msg>').fadeIn( 200 );
$( '#messageBox > msg:last-of-type' ).delay(3000).fadeOut( 3000 );
setTimeout(function(){
$( '#messageBox > msg:first-of-type' ).remove();
}, 5999);
}
// This test message bellow works correctly.
returnedMessage('hello world - test 1');
});
EDIT:
you should define your function like so:
var someFunction = function() {
// do something
}
Or like so
function someFunction() {
// do something
}
But always use the function word. More information on function definition in Javascript.
More about JS file import
Javascript code is inserted between <script> tags in an HTML file
<script>
console.log("Hello World!");
</script>
You usually place those script tags inside the <head> tag. However it's recommended you put them after your <body>. This way you allow the DOM to load before you run your JS script. This is important for exemple when you want to select elements in the DOM. If you put the JS code before the actual HTML that creates this element, then JS will not find the element you would be looking for because it doesn't yet exist.
Now it's not really efficient to work with script in your HTML code so it's helpful to write JS in .js files and then import them in you HTML file like you would for a CSS file. Use the <script> to do so:
<script src="myScript.js"></script>
You can use multiple <script> tags to pull in multiple JS files. But you need to be careful of the order you write them. For instance you have a functions.js file that holds all your functions, and a menu.js that handles the menu on your application. You're using functions from the code functions.js in menu.js so you need to import the files in this order:
<script src="functions.js"></script>
<script src="menu.js"></script>
First declared, first loaded.
You can write own function like this:
Here you can see simple example: https://jsbin.com/munowupipo/edit?html,output
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Define a Function in jQuery</title>
<script src="https://code.jquery.com/jquery-2.1.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$.fn.myFunction = function() {
alert('You have successfully defined the function!');
}
$(".call-btn").click(function(){
$.fn.myFunction();
});
});
</script>
</head>
<body>
<button type="button" class="call-btn">Click Me</button>
</body>
</html>
Maybe you want to take the function on document is ready, so you must to write:
<script>
$(document).on("ready", function() { yourfunction(); });
</script>
HI i am facing some problem while calling function from index.html on load event
it return error readjson is not defined in console.
index.html
<script type="text/javascript">
$(window).load(function () {
readjson('a','s');
});
</script>
main.js file
<script type="text/javascript">
function readjson(val1,val2){
//some code
}
</script>
Can anyone tell me why it is not able to call, i have link main.js file to index.html
JavaScript files shouldn't include any HTML.
Remove <script type="text/javascript"> and </script> from main.js.
You should see an error when that file is loaded (along the lines of Unexpected token <).
Call it like this inside the js file without the "script" tag :
function readjson(val1,val2){
//some code
}
In index.html you need the "script"
And follow the advice given in the comments, always include first the .js file and then the function in the index.html
Did you add jquery link properly??
If not, you should add jquery link for $(window) to be called. such as..
<script src="http://code.jquery.com/jquery-latest.js"></script>
If you actually have two script declarations as you are showing here the the window load will fire first. It then look for your function, which has not been created yet. That's why you are getting undefined.
You could have one script declaration on the page and place your function in the load function.
<script>
$(window).load(function () {
readjson('a','s');
function readjson(val1,val2){
//some code
}
});
</script>
Remove tags from main.js:
<script type="text/javascript"> and </script>
and remember to include jquery and main.js with:
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.1.4.min.js"></script>
<script src="test.js"></script>
When i am trying to write the code like
document.getElementById('id1') after teh script tag it is showing document.getElementById(..) null or not an object..
Is it necessary to write document.getElementById('id1') in function only.
If i write this code in function then it is accepting. So what the mistake here..
and if i want to execute a function on loading of the page where to write onLoad() function.. i try to write at but it is not loading.. please help me
Thank you
In order to be sure that your dom element is loaded, you have to wait the document is loaded.
To do this you can do:
<head>
<script type="text/javascript">
function foo(){
var elem = document.getElementById("yourElem");
//...
}
</script>
</head>
<body onload="foo()">...</body>
or
<head>
<script type="text/javascript">
function foo(){
var elem = document.getElementById("yourElem");
//...
}
window.onload = foo;
</script>
</head>
<body>...</body>
If you want the script to run after the page is loaded, you can use window.onload.
<script>
window.onload = function () {
//code goes here
}
.
.
.
</script>
Put your script bellow the element you are getting will also work.
<div id="ele"></div>
<script language="javascript">
alert(document.getElementById('ele').tagName);
</script>
<div id="ele1"></div>
But unless you have special purpose, it's a good habit to write handlers in after document loaded, that is, put your code in window.onload event handler.