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>
Related
I have an external Javascript file initialize_database.js that uses JQuery to call a PHP script to create a database and some tables. I've tested my PHP script by adding some HTML to it to run it on its own, and it works fine. My HTML is as follows:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<title>Test Webpage</title>
</head>
<body>
<script src="initialize_database.js"></script>
<div>
<h2>Nothing here yet!</h2>
</div>
</body>
</html>
Here is initialize_database.js:
$(document).ready(function() {
$.get('testPhp.php' {
alert('Databases were initialized');
});
});
I'd like to have the Javascript run as soon as the page loads so that the database can be created right away. All files are in the same directory. What am I doing wrong?
Comma and function initialization is required after the URL for executing the function correctly.
$(document).ready(function() {
$.get('testPhp.php', function() {
alert('Databases were initialized');
});
});
Check this
you can use this code . if you want to run when dom ready then
$(document).ready(function() {
$.get('testPhp.php', function() {
alert('Databases were initialized');
});
});
if you want to run this full load then use bellow
$( window ).load(function() {
$.get('testPhp.php', function() {
alert('Databases were initialized');
});
});
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>
So, lets say you have a page that wants to load from a javascript file and it includes
temp.html file
<script src="example.js"></script>
<p class="one"></p>
Now in the example.js file you have a function that is
function getInfo() {
var place = "foo"
$(".one").html(place);
}
//Edit currently I call the function inside the JS file
getInfo();
My question is how would you connect the two files so that the external javascript file knows that it is pointed to the paragraph with the class one?
Normally when this is in a single page, you would call the function and the info will be set.
I have seen a getScript method and a load method for Jquery. Would that be applicable here?
Any ideas on how to approach this? If you provide some code that will be super helpful.
Thanks in advance.
Looks like you want to execute getInfo() as soon as it's defined (i.e.: example.js is loaded).
You can try this approach:
<script src="example.js" onload="getInfo();"></script>
In your example.js, change getInfo() to something like this:
function getInfo() {
$(document).ready(function() {
var place = "foo"
$(".one").html(place);
});
}
Your language is confusing, but you could use jQuery's $(document).ready function which would suffice. Generally speaking, an externally loaded file should execute where the tag is in the script.
A hack could be to place a tag before the end of your document body, give it an id, and then use $('#id').ready() there. In general though, you could just try coding the transclusion concept (I'm guessing you're used to this) from scratch using intervals and timeouts.
<div id="rdy">
</div>
</body>
Then in your file:
$('#rdy').ready(getInfo);
Just my added opinion, you should consider that Google is up to some not-so-nice things these days, they are long-gone from the "do no evil" mantra.
If we assume you have a JavaScript file that contains this content:
function getInfo() {
var place = "foo"
$(".one").html(place);
}
then your markup will look something like this:
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="example.js"></script>
<script>
$(function(){
getInfo();
});
</script>
</head>
<body>
<p class="one"></p>
</body>
</html>
$(function(){ ... }); is just the simplified version of $(document).ready(function(){ ... });. They both more or less handle the onload event, which fires when page has finished loading.
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>
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.