call javascript method directly from html - javascript

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>

Related

Javascript function not found in node.js server

I followed this to set up the node.js server: Using node.js as a simple web server
So I installed the serve-static npm.
I then created a file called file called test.html with the following code
<html>
<head>
<h2>Google</h2>
</head>
<body>
<button onclick="test()">Click me</button>
</body>
</html>
<script src="http://code.jquery.com/jquery-3.3.1.min.js" type="text/javascript">
function test() {
console.log('test');
}
</script>
When I click on the button, I get:
Uncaught ReferenceError: test is not defined
at HTMLButtonElement.onclick (test.html:8)
and nothing else. This code looks ok...? Why is this function not found?
Remove your src part if you want to have your own function in between your script tags.
<script src="http://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
function test() {
console.log('test');
}
</script>
Also, you should put your scripts before your </body>
Put your javascript just before closing body tag (</body>)
And in your case you are binding event handler in the html itself, in this case you have to define those functions before you use them.
In this case put test() function code in head tag. It will work fine
Your JavaScript (script tag) is outside of html element. Put it in head or body.

Pure js invoking functions on async script (external file) within body tags

I am writing a script using pure js involving a js snippet that is copied into cleint websites. When invoking a pure js function myfunction() like below the function will run, no need for document.ready, onload etc:
<body>
<script>
function myfunction(){}
myfunction()
</script>
</body>
So my question is if I load an external file like this below, will the js function execute with simply myfunction() and across all browsers.
<body>
<script type="text/javascript"async=""src="anotherwebsite.com/jsfile.js"></script>
</body>
jsfile.js contents
function myfunction(){}
myfunction()
What happens If you dynamically load in a <script> tag it will be executed asynchronous by default. So the code will be executed and myfunction will be invoked. If you want your code to be synchronously you can set the async attribute to false like this:
<script type="text/javascript" async="false" src="anotherwebsite.com/jsfile.js" ></script>
More on async in MDN Docs.

how to call a javascript function from another 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.

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.

how must my javascript look like to run at the end of my ASP.NET page

this code is put at the top of my asp.net page:
function Test(HtmlDocument)
{
}
How can I execute this javascript function at the end of my page?
Just invoke the function in <script> tags immediately before the </body> tag.
<html>
<head>
<!-- snip -->
</head>
<body>
<!-- snip -->
<script>
Test(document);
</script>
</body>
</html>
Simply put
<script>Test(document);</script>
In the end of your html
The best way to achieve this is using windows.onload. The event can be used to perform some task as soon as the page finishes loading. Here is an example:
<script type="text/javascript">
function my_code(){
alert(" Alert inside my_code function");
}
window.onload=my_code();
</script>
Or you can put the function at the bottom of the code without the function declaration
<script>
Your javascript code here
</script>
The easy way is to drop a script manager on the page (anywhere within the body of the page) then put something like this on the page ...
<script type="text/javascript">
Sys.Application.add_load(function () {
// do your thing
});
</script>
That executes client side when the document has finished loading.

Categories