Javascript function not executing when another function is above it - javascript

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();
}

Related

Socket JS not works inside onload method

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.

LocalStorage set property 'innerHTML' of null. Tried solution with window.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);
}

What is the scope of a JavaScript function? [duplicate]

I'm not quite sure what goes on between <script> tags. For example, the following gives a reference error and type error in Chrome:
<html>
<head>
<script type="text/javascript">
T.prototype.test = function() {
document.write("a");
}
</script>
<script type="text/javascript">
function T() {}
var v = new T();
v.test();
</script>
</head>
<body>
</body>
</html>
But this works:
<html>
<head>
<script type="text/javascript">
</script>
<script type="text/javascript">
T.prototype.test = function() {
document.write("a");
}
function T() {}
var v = new T();
v.test();
</script>
</head>
<body>
</body>
</html>
The upper script is executed first in the first example, so it doesn't know about T yet, hence the error.
In the second example, T is well defined and known anywhere as soon as the script tag is executed. This is due to function declarations being hoisted to the top, no matter what the order is, they are always available. Function declaration hoisting is more deeply explained here
The second example after hoisting is applied:
var v,
T = function(){}; /* using comma like this is short-hand for: var v; var T = function(){}; */
T.prototype.test = function() {
document.write("a");
};
v = new T();
v.test();
They are each parsed in the global context, but in order. The entire first script tag is parsed and executed before the second one is considered. As part of parsing a script, function declarations are recognized ahead of time, which is why the second one works while the first one doesn't.

after using parenthesis () my function not running?

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>

Why JavaScript function visibility depends on declaration in the same or different script block in HTML

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.

Categories

Resources