how to call a javascript function from another javascript? - javascript

how can i call webService() from one in another script when they are in the same html file.
first script that call method from second script
<script type="text/javascript">
function validate(){
//validate body
//how to call webService() here;
}
</script>
second script
<script type="text/javascript">
function webService(){
//WEB SERVICE FUNCTION BODY
}
</script>
html :
<input type="button" value="Login" id="loginButton" onclick="validate();">

What you could do is use a global wrapper arround functions
<html>
<head>
<script type="text/javascript">
function validate(){
alert("calling Script1")
if(WRAPPER) WRAPPER.webService()
}
</script>
</head>
<body>
<script type="text/javascript">
var WRAPPER = {}
WRAPPER.webService = function(){
alert("Script1")
}
</script>
<input type="button" value="Login" id="loginButton" onclick="validate();">
</body>
</html>
Although if the function is called directly from the head, the script at the body would not have loaded. You might need to wrap validate() around
document.addEventListener('DOMContentLoaded', function() {
validate()
}, false);`

The same way you would normally call a javascript function. Benjamin Gruenbaum states you should declare the function webService before the validate function.
<script type="text/javascript">
function webService(){
//WEB SERVICE FUNCTION BODY
}
</script>
<script type="text/javascript">
function validate(){
//validate body
webService();
}
</script>

Usually you would put the code in two different js files and include the webService before the validate, which would make the one function available before the other.
<body>
// other code
<script src="scriptWithWebService.js"></script>
<script src="scriptWithValidate.js"></script>
</body>

This has everything to do with scope. All Javascript elements are parsed in sequence. First the ones in the head and then the ones in the body. Functions are parsed first and aren't executed when they are defined. Declarations and function calls are executed afterwards. example:
<script>
runCode();
function runCode()
{
alert(1);
}
</script>
Will work, since the function runCode is defined first while parsing, however this example will fail:
<script>
runCode();
</script>
<script>
function runCode()
{
alert(1);
}
</script>
This will fail, runCode is called before it's defined, since the second script block isn't parsed yet. The following example will work:
<script>
function runCode()
{
runUpdate()
}
</script>
<script>
function runUpdate()
{
alert(1);
}
runCode();
</script>
Even though runUpdate isn't defined when runCode is parsed it will not raise an undefined error since the content of the function isn't executed until called upon.
So at the end of the document loading, all the Javascript is parsed into a global scope. (Or simplified: it's put onto one big pile).
So when the document is loaded the code looks like this:
function validate(){
//validate body
//how to call webService() here;
}
function webService(){
//WEB SERVICE FUNCTION BODY
}
and your input with click event can call upon validate() and validate can call upon webservice because there both defined.

Related

Call function in .js file from html?

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>

call javascript method directly from html

Hello I want to call javascript method directly from jsp.Here is my dummy code in this javascript method print1() is not calling.
<html>`
<body>
<h1>hello</h1>
<script>print1()</script>
<p>hii</p>
<script>
function print1(){
alert("hello");
document.getElementsByTagName("p").innerHTML="hey";
}
</script>
</body>
</html>
Solving this can help me to great extent.
Note-I can't call it using onload as this is only dummy code I have to apply logic to some other code
First, there are a few syntax errors in your code that need to be fixed.
Then, You will need to call the function after it is defined (or in the same <script> tag). Function hoisting does not hoist print1() in time. That is because the browser tries to execute the script as soon as it encounters it. This means when the browser sees <script>print1()</script>, it is not even aware of the rest of the file.
So you need to invoke print1() after the function is defined. In addition to the solutions in comments and the other answer, another option would be to put the script in a separate file and invoke it with defer.
printFunc.js:
print1();
In the html file:
<script src="printFunc.js" defer></script>
This will invoke print1(). Note that defer does not work if the script is not external.
Just for fun (and To see how the browser goes through <script> tags), you can even invoke the function via setTimeout:
<script>
setTimeout(function(){ print1(); }, 3000);
</script>
<script>
function print1(){
alert("hello");
document.getElementsByTagName("p").innerHTML="hey";
}
</script>
There are two options to fix the issue:
Option1: Move the call <script>print1()</script> to the end of the file (i.e., define the function first before the call and look here for clear explanation on this)
Option2: Call it during the body onload as shown below:
<body onload="print1()">
</body>
Firstly its that you can call it in body tag as "onload", Secondly "getElementsByTagName" returns array so you have to tell at which array position you want to make your change
<html>`
<body onload= "print1()">
<h1>hello</h1>
<p>hii</p>
<script>
function print1(){
alert("hello");
document.getElementsByTagName("p")[0].innerHTML="hey";
}
</script>
You can do this way also
<html>`
<body>
<h1>hello</h1>
<p>hii</p>
<script>
function print1(){
alert("hello");
document.getElementsByTagName("p")[0].innerHTML="hey";
}
</script>
<script>print1();</script>
</body>
</html>

Why is external javascript library blocking javascript on my page?

Here's a very simple question that my simple mind can't answer: why isn't the anonymous and onload function below being run when I load in the external library? I am missing something really, really basic. Library.js has only one line: console.log('library'). How much more basic can one get?
<script type="text/javascript" src='js/library.js' />
<script type="text/javascript">
(function () {
console.log('anon');
})();
window.onload = function () {
console.log('onload');
} ();
</script>
Your script syntax is invalid. You should have a separate closing tag instead of the self-closing version.
<!--------- v --------->
<script type="text/javascript" src='js/library.js'></script>
You also have an issue in that you're invoking the onload function immediately.
window.onload = function () {
console.log('onload');
}/* () */;
// ^^---remove these to assign the function instead of invoking it.

javascript defines scope by script tags?

Never met this problem, and don't know why.
The only explanation is a scope issue.
In the same page, I have 2 sections of JS :
...
<script type="text/javascript">
go();
</script>
<script type="text/javascript">
function go()
{ alert(''); }
</script>
...
This will show an error : go is not defined
where
...
<script type="text/javascript">
go();
function go()
{ alert(''); }
</script>
...
is working (obviously).
Does <script> tag creates a scope of JS ?
help ?
This isn't a scope issue. If you define a function (in the global scope) in one script element, then you can use it in another.
However, script elements are parsed and executed as they are encountered.
Hoisting won't work across script elements. A function defined in a later script element won't be available during the initial run of an earlier script element.
You either need to swap the order of your script elements, or delay the function call until after the script that defines it has run (e.g. by attaching it to an onload event handler).
<script>
function go() {
alert('');
}
</script>
<script>
go();
</script>
or
<script>
window.addEventListener("load", function () {
go();
}, false);
</script>
<script>
function go() {
alert('');
}
</script>
The html parser stops to execute your script before moving to next elements. So the next script element
is not executed until the first one is executed.
This is comparable to:
<script>
document.getElementById("hello") //null because the html parser hasn't met the div yet.
</script>
<div id="hello"></div>
The other cause of this as an apparent error is if the first script block has a syntax error and is rejected in its entirety, but the second block runs on and misses its buddy code.
As it's been said already, order matters. For what it's worth, I saw this issue with an experiment (not production!) where I had something like this:
<head>
<script src="/path/one.js" defer>
</head>
<body>
<script>
methodInOneJs();
</script>
</body>
And the browser complained with a ReferenceError, even though methodInOneJs() was defined in one.js. This because of the defer attribute in the script that loads it. One might think that putting defer in the inline script as well would solve the issue, but according to MDN:
Warning: This attribute must not be used if the src attribute is
absent (i.e. for inline scripts), in this case it would have no
effect.
One quick solution (aside from removing defer altogether) was to use the onload event (again, not production, where I'd just use src):
<head>
<script src="/path/one.js" defer>
</head>
<body onload="run();">
<script>
function run()
{
methodInOneJs();
}
</script>
</body>
This is because with defer:
the script is meant to be executed after the document has been parsed,
but before firing DOMContentLoaded.
Emphasis on "before firing DOMContentLoaded". See also how to load scripts last.

javascript loading problem

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.

Categories