My first code working but second code not working after adding () parenthesis after myFunction. What is the reason?
Code1
<script type="text/javascript">
function myFunction(){
var status = document.getElementById("status");
status.innerHTML = "The page finishing loading made my function run.";
}
window.onload = myFunction;
</script>
<h3 id="status"></h3>
Code 2
<script type="text/javascript">
function myFunction(){
var status = document.getElementById("status");
status.innerHTML = "The page finishing loading made my function run.";
}
window.onload = myFunction();
</script>
<h3 id="status"></h3>
In first case you're assigning the reference of the function which will be used in callback.
In your second case you're assigning the value that is being returned by the function which is in this case undefined as you're not returing anything.
window.onload or any event handler for that matter, expects a function reference to be executed on callback.
window.onload is an event handler and must be a function, not the result of function. of course you may leave parenthesis, but in this way your function myFunction should return another function
<script type="text/javascript">
function myFunction(){
return function() {
var status = document.getElementById("status");
status.innerHTML = "The page finishing loading made my function run.";
}
}
window.onload = myFunction();
</script>
<h3 id="status"></h3>
Related
I have this js piece which I use for django channels:
var chatSocketSender1 = new WebSocket(
'ws://' + window.location.host + '/ws/my_socket1/'
)
function send() {
var msg = "some message"
var receiver_id = 111
window['chatSocketSender1'].send( JSON.stringify({
'msg': msg,
'receiver_id': receiver_id
}) )
}
document.querySelector('#send_button').onclick = function() {
send();
}
The problem is that this js code only works if I put that after latest element of HTML:
<head>
...
</head>
<body>
// whole html content here
<script>
// js piece here
</script>
</body>
But if I use jquery's on load method like:
<head>
<script>
$(window).on('load', function () {
// js piece here
});
</script>
</head>
<body>
// whole html content here
</body>
Then it gives: Uncaught TypeError: window[("chatSocketSender1")] is undefined
Any suggestion please, why this not works with "onload" ?
The reason your code doesn't work is because in your first code var chatSocketSender1 creates a "global" variable (that's defined at the window level) that you later reference as window("chatSocketSender1"), but in the second code, var chatSocketSender1 is scoped to the anonymous event handler function, so is not available as window("chatSocketSender1").
Put another way:
<script>
var x = 1;
function foo() {
console.log(x)
}
</script>
works fine, but
<script>
function foo() {
var x = 1;
}
foo();
console.log(x);
</script>
will give an undefined variable error as x only exists inside foo. This isn't exactly what you've done, but is essentially the same concept.
Now, if your code was:
chatSocketSender1.send(
then it would have worked fine as your variable chatSocketSender1 is defined within the function() { onload event callback.
or instead of
var chatSocketSender1 =
you could do
window.chatSocketSender1 =
to define the variable globally, or you could:
<script>
var chatSocketSender1 = new WebSocket(...
function send() { ... }
$(window).on('load', function () {
document.querySelector('#send_button').onclick = ...
as you generally only need the event binding within the onload.
I have a javascript that tries to get the information from the localStorage. Either i haven't fully understood window.onload or something else is faulty.
Thanks in advance!
onClickJs.js
function onClickLight() {
alert("OnClick Log " + window.onload);
window.onload = function (){
var statusPub = document.getElementById("result").innerHTML = localStorage.getItem("statusPub");
console.log(statusPub);
}
index.jsp
<script>
function load() {
console.log("load event detected!");
}
window.onload = load;
</script>
<button type="lightButton" onclick="onClickLight()">Light</button>
By the time you click the button, the window load event has already fired. So assigning a function to window.onload at that point is useless, the function will never be called.
If you want to do the work that function is doing, just...do it:
function onClickLight() {
var statusPub = document.getElementById("result").innerHTML = localStorage.getItem("statusPub");
console.log(statusPub);
}
I am using this innerhtml property to print my output from javascript into a div in html. I have checked other topics with the same problem, but nothing seems to work.
The following code is all between the 'body' tags in my html.
Code:
<script> function firstGame(); </script>
<div id="outputgame"> </div>
<button onclick="functionGame()"> Starten </button>
<script type="text/javascript">
function firstGame()
{
var output = document.getElementById('outputgame');
output.innerHTML('<p>First test</p>');
// Check if the user is ready to play!
confirm("Are you ready to play this epic game?")
var age = prompt("What is your age?");
if (age < 13)
{
document.getElementById('outputgame').innerHTML= "You are to young to play this game. You can proceed, however i do not take any responsibility";
}
else
{
document.getElementById('outputgame').innerHTML= "Sweet, Let's go!";
}
}
</script>
Let's talk about page rendering upon initialization and global scope. A scope is the context in which values and expressions are "visible," or can be referenced. The global scope is the context for the whole document. If a value or function is declared here it's visible in every function or expression.
The JavaScript in your page is being parsed one script block at a time. When the script block is parsed without errors the script block is transferred into the global scope. The thread (stored in the window object) where all public values and expressions are available.
Functions are parsed first, then the rest of the block. However script blocks are parsed one at a time I wrote earlier. So if you make a call to a function not yet in the global scope since it's in another script block that hasn't been parsed yet your code will fail and throw and undefined error.
Consider this:
<script>
function test()
{
alert(1);
}
test();
</script>
A nice alert is shown. the function test is parsed first and test is executed thereafter.
<script>
test();
function test()
{
alert(1);
}
</script>
This also works. Since functions are parsed first test() still works and alerts 1.
<script>
test();
</script>
<script>
function test()
{
alert(1);
}
</script>
This however won't work. Since the function test in the second script block isn't yet parsed calling test() will result in a script error.
<script>
function test()
{
alert(1);
}
</script>
<script>
test();
</script>
This does work. The function is declared first and added to the global scope. In the second script block test() looks for a function test in the global scope, finds it and executes it.
This is the explanation above applied to your code:
<div id="outputgame"> </div>
<button onclick="functionGame()"> Starten </button>
<script type="text/javascript">
function firstGame()
{
var output = document.getElementById('outputgame');
output.innerHTML = '<p>First test</p>';
// Check if the user is ready to play!
// Do you really need this?
//Confirm returns a Boolean (true or false), you can do something with the result. If not just show an alert or nothing. Latter is preferred.
confirm("Are you ready to play this epic game?")
var age = prompt("What is your age?");
//You should make this more robust. What if someone enters "asaaslk". Use a select box with birth years.
if (age < 13)
{
document.getElementById('outputgame').innerHTML = "You are to young to play this game. You can proceed, however i do not take any responsibility";
}
else
{
document.getElementById('outputgame').innerHTML = "Sweet, Let's go!";
}
}
</script>
<script> function firstGame(); </script>
<div id="outputgame"> </div>
<button onclick="firstGame()"> Starten </button>
<script type="text/javascript">
function firstGame()
{
var output = document.getElementById('outputgame');
output.innerHTML = '<p>First test</p>';
// Check if the user is ready to play!
confirm("Are you ready to play this epic game?")
var age = prompt("What is your age?");
if (age < 13)
{
document.getElementById('outputgame').innerHTML= "You are to young to play this game. You can proceed, however i do not take any responsibility";
}
else
{
document.getElementById('outputgame').innerHTML= "Sweet, Let's go!";
}
}
</script>
HTML
<div id="outputgame"> </div>
<button onclick="firstGame()"> Starten </button>
javascript
<script type="text/JavaScript">
function firstGame()
{
var output = document.getElementById('outputgame');
output.innerHTML='<p>First test</p>';
// Check if the user is ready to play!
confirm("Are you ready to play this epic game?")
var age = prompt("What is your age?");
if (age < 13)
{
document.getElementById('outputgame').innerHTML= "You are to young to play this game.You can proceed, however i do not take any responsibility";
}
else
{
document.getElementById('outputgame').innerHTML= "Sweet, Let's go!";
}
}
</script>
Two problems: You named your function the wrong name?, and you are calling innerHTML as a function instead of assigning it a value.
Also, where is functionGame() defined? You cannot use forward declarations like in C.
function firstGame() {
var output = document.getElementById('outputgame');
var text = '';
output.innerHTML = '<p>First test</p>';
// Check if the user is ready to play!
confirm("Are you ready to play this epic game?")
var age = parseInt(prompt("What is your age?"), 10);
if (age < 13) {
text = "You are to young to play this game. You can proceed, however I do not take any responsibility.";
} else {
text = "Sweet, Let's go!";
}
document.getElementById('outputgame').innerHTML = text;
}
<div id="outputgame"></div>
<button onclick="firstGame()">Starten</button>
So, the function "txtLoad()" will not execute while "txtFunc()" is being called by an onLoad function.
<!DOCTYPE html>
<html>
<head>
<title>Page</title>
</head>
<body>
<textarea id="Text" rows="20" cols="70"></textarea>
<script>
function txtFunc(){
var q=1;
}
function txtLoad() {
document.getElementById("Text").innerHTML = "Hello";
}
onload=function(){
txtLoad()
}
onload=function(){
txtFunc()
}
</script>
</body>
</html>
The JavaScript engine says there is nothing wrong with the code inside the "script" element. Does anyone know why the function isn't executing?
your second onload= replaced the function that calls txtLoad, if you want to run both:
onload = function () {
txtLoad();
txtFunc();
};
Also there seems to be extra "}" after the txtFunc.
How can two functions be defined to the onload. For eg:
var x = 1
var x = 2
What do you think the value of x is going to be? Obviously 2.
You are overwriting the onload. Its only going to execute the stuff which you assigned at last.
You could do this to achieve what you want.
onload = init()
function init() {
textLoad();
textFunc();
}
simply because the first onload was overwritten by the las onload.
function txtFunc(){
var q=1;
}
function txtLoad() {
document.getElementById("Text").innerHTML = "Hello";
}
onload=test();
function test()
{
txtLoad();
txtFunc();
}
If I implement the following JavaScript code block in HTML markup:
<script type="text/javascript">
function MyFunc() {
alert(1);
}
var f1 = MyFunc;
</script>
<script type="text/javascript">
function MyFunc() {
alert(2)
}
</script>
<script type="text/javascript">
f1();
</script>
I get an alert message '1'.
However, if I use the following code:
<script type="text/javascript">
function MyFunc() {
alert(1);
}
var f1 = MyFunc;
function MyFunc() {
alert(2)
}
</script>
<script type="text/javascript">
</script>
<script type="text/javascript">
f1();
</script>
I get '2'. Why?
Tested in IE10, latest FF, Chrome.
This is caused by hoisting. var and function declarations are hoisted to the top of the script block they are in.
This means that your first script essentially becomes:
var f1;
function MyFunc() {
alert(1);
}
f1 = MyFunc;
// new script block
function MyFunc() {
alert(2)
}
// new script block
f1(); // alert 1
Meanwhile, your second script becomes:
var f1;
function MyFunc() {
alert(1);
}
function MyFunc() { // overwrite previous MyFunc
alert(2)
}
f1 = MyFunc;
// new script block
f1(); // alert 2
I hope this makes sense - just in general avoid overwriting functions XD
Each script element is parsed and executed in order. In the first case, the assignment to f1 is made before the second declaration is processed.
In the second case, both declarations are parsed before the assignment is made (because declarations are processed before any code is executed), so the second declaration replaces the first before the assignment to f1.
I hope I don't confuse anybody, but, I suspect the answer has something to do with scopes.
Here is my argument:
For the 1st case:
<script type="text/javascript">
function MyFunc() {
alert(1);
}
var f1 = MyFunc;
window.foo1 = MyFunc;
</script>
<script type="text/javascript">
function MyFunc() {
alert(2)
}
window.foo2 = MyFunc;
</script>
<script type="text/javascript">
f1();
alert(window.foo2 === window.foo1);
</script>
The second alert will issue a false.
Now the 2nd case.
<script type="text/javascript">
function MyFunc() {
alert(1);
}
var f1 = MyFunc;
window.foo1 = f1;
function MyFunc() {
alert(2)
}
window.foo2 = MyFunc;
</script>
<script type="text/javascript">
</script>
<script type="text/javascript">
f1();
alert(window.foo1 === window.foo2);
</script>
The second alert will issue a true.
It kind of shows that (for 1st case) MyFunc is redefined and is a totally different "object" when the 2nd script block is processed. f1 holds a reference to the first "object" in the first script block. Hence f1() alerts 1.
For the first part with alert message 1 the declaration var f1 = MyFunc; becomes similar to a local wrt different <script> blocks.Hence the <script> block in which var f1 is defined it performs the function contained in that block.
For the second part with alert message 2 , 1st MyFunc() is overwritten by the second.